Default arguments allow a function to be called without providing all the required parameters. By assigning a default value to a parameter, Python automatically uses that value when no argument is supplied during the function call.
This feature improves flexibility and reduces the need to pass repetitive values.
A default argument is a parameter that has a predefined value assigned in the function definition. If the caller does not provide a value for that parameter, the default value is used.
def function_name(parameter = default_value):
# code block
def greet(name="Guest"):
print("Hello,", name)
Function Calls:
greet("Alice")
greet()
Output:
Hello, Alice
Hello, Guest
def power(base, exponent=2):
return base ** exponent
Calls:
print(power(3)) # uses default exponent
print(power(3, 3)) # overrides default
Output:
9
27
Parameters with default values must come after non-default parameters.
✔ Correct:
def func(a, b=10):
pass
✘ Incorrect:
def func(a=10, b):
pass
Default values can be overridden by passing arguments during the function call.
def show(price=100):
print(price)
show() # 100
show(250) # 250
Using mutable objects (like lists or dictionaries) as default arguments can lead to unexpected behavior.
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item(1))
print(add_item(2))
Output:
[1]
[1, 2] # unexpected behavior
Reason: The same list is reused across function calls.
✔ Correct approach:
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
Default arguments are evaluated only once at the time of function definition, not each time the function is called. This is especially important when dealing with mutable data types.
Default arguments provide a convenient way to design flexible and user-friendly functions in Python. However, they must be used carefully, especially with mutable objects, to avoid unintended side effects.