Function Arguments In Python
Python Function Arguments: Deep Dive
In Python, there are multiple ways to pass information (arguments) to a function. Understanding these helps you write more flexible and powerful code.
1. Positional Arguments
The most common way. Arguments are assigned to parameters based on their order.
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet("Hamster", "Harry") # Order matters!
2. Keyword Arguments
You can pass arguments using the name=value syntax. This makes the order irrelevant.
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet(pet_name="Harry", animal_type="Hamster") # Order doesn't matter
3. Default Values
You can define a default value for a parameter. If the argument is missing when calling, the default is used.
def describe_pet(pet_name, animal_type="Dog"):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet("Willie") # Uses default "Dog"
describe_pet("Harry", "Hamster") # Overrides default
*args
Use * before the parameter name if you don't know how many arguments will be passed. Python receives them as a Tuple.
def list_fruits(*fruits):
for fruit in fruits:
print(f"Fruit: {fruit}")
list_fruits("Apple", "Banana", "Cherry", "Mango")
**kwargs
Use ** if you want to pass an unknown number of keyword arguments. Python receives them as a Dictionary.
def user_profile(**user_info):
for key, value in user_info.items():
print(f"{key}: {value}")
user_profile(name="Tanis", age=25, city="Mumbai", role="Developer")
6. Quick Comparison
| Argument Type | Syntax | Received As | Key Benefit |
| :--- | :--- | :--- | :--- |
| Positional | val | Local Variable | Fast and Simple |
| Keyword | key=val | Local Variable | Clearer Code |
| Default | def f(a=1) | Optional Var | Flexible Functions |
| *Arbitrary (args) | *args | Tuple | Handle many inputs |
| **Arbitrary Kwargs (kwargs) | **kwargs | Dictionary | Handle named options |
7. Combining All Types
If you use all types in one function, they MUST be in this order:
Standard -> *args -> Default -> **kwargs
def complex_function(a, b, *args, city="Mumbai", **kwargs):
print(a, b, args, city, kwargs)
complex_function(1, 2, 3, 4, 5, city="Delhi", status="Active")