Default and Variable Args
Default Arguments
Default arguments allow functions to have predefined values for parameters, making them optional during function calls.
def create_profile(name, age=25, city="Unknown"):
return f"Name: {name}, Age: {age}, City: {city}"
## Different ways of calling the function
print(create_profile("Alice")) ## Uses default age and city
print(create_profile("Bob", 30)) ## Overrides age
print(create_profile("Charlie", city="New York")) ## Specifies city
Important Considerations for Default Arguments
Scenario |
Behavior |
Best Practice |
Mutable Default |
Can lead to unexpected results |
Avoid mutable defaults |
Order of Arguments |
Default args come after required args |
Follow Python conventions |
Variable Arguments (*args)
Variable arguments allow functions to accept any number of positional arguments.
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3)) ## Output: 6
print(sum_numbers(10, 20, 30, 40)) ## Output: 100
Variable Arguments Visualization
graph TD
A[*args] --> B[Collects Multiple Arguments]
A --> C[Creates Tuple of Arguments]
A --> D[Flexible Function Inputs]
Combining Default and Variable Arguments
def flexible_function(x, y=10, *args):
total = x + y
for arg in args:
total += arg
return total
print(flexible_function(5)) ## Output: 15
print(flexible_function(5, 20, 1, 2, 3)) ## Output: 31
Best Practices
- Use default arguments for optional parameters
- Leverage *args for functions with variable input
- Be mindful of argument order and type
At LabEx, we emphasize understanding these advanced parameter techniques to write more flexible and robust Python functions.