Python Function Arguments
Function arguments in Python define how data is passed to functions. Python supports several types of arguments:
1. Positional Arguments
These are the most common type. Arguments are matched by position.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25)
Output:
Hello Alice, you are 25 years old.
2. Keyword Arguments
Arguments can also be passed using name=value
syntax, regardless of their order.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=25, name="Alice")
Output:
Hello Alice, you are 25 years old.
3. Default Arguments
Provide default values for parameters so they become optional.
def greet(name="Guest"):
print(f"Hello {name}")
greet() # Uses default
greet("Alice") # Overrides default
Output:
Hello Guest
Hello Alice
4. Arbitrary Positional Arguments (*args
)
Used when you want to allow any number of positional arguments. These are received as a tuple.
def add_numbers(*args):
total = sum(args)
print("Sum:", total)
add_numbers(1, 2, 3)
add_numbers(5, 10)
Output:
Sum: 6
Sum: 15
5. Arbitrary Keyword Arguments (**kwargs
)
Used to handle any number of keyword arguments. These are received as a dictionary.
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25)
Output:
name: Alice
age: 25
Combining Different Argument Types
Order of arguments must be:
def func(positional, /, positional_or_keyword, *, keyword_only)
Typical combination:
def example(a, b=2, *args, **kwargs):
print("a:", a)
print("b:", b)
print("args:", args)
print("kwargs:", kwargs)
example(1, 3, 4, 5, x=10, y=20)
Output:
a: 1
b: 3
args: (4, 5)
kwargs: {'x': 10, 'y': 20}
Special Types (Python 3.8+)
1. Positional-Only Parameters (/
)
def add(x, y, /):
return x + y
print(add(2, 3)) # OK
# print(add(x=2, y=3)) # Error!
2. Keyword-Only Parameters (*
)
def greet(*, name):
print("Hello", name)
greet(name="Alice") # OK
# greet("Alice") # Error!
Summary Table
Type | Symbol | Description |
---|---|---|
Positional | – | Based on order |
Keyword | – | Based on parameter names |
Default | = | Parameter has default value |
Arbitrary Positional | *args | Multiple unnamed positional arguments |
Arbitrary Keyword | **kwargs | Multiple named keyword arguments |
Positional-only | / | Must be passed positionally |
Keyword-only | * | Must be passed by name |
Practice Task
def user_info(name, age=18, *skills, **extra):
print("Name:", name)
print("Age:", age)
print("Skills:", skills)
print("Extra Info:", extra)
user_info("Tom", 20, "Python", "Django", city="Delhi", married=False)
Output:
Name: Tom
Age: 20
Skills: ('Python', 'Django')
Extra Info: {'city': 'Delhi', 'married': False}