5.4 Defaults, *args, **kwargs
We explore advanced techniques for creating flexible functions that accept default values and a variable number of arguments.
Default Parameter Values
You can make a parameter optional by giving it a default value in the function definition. If the user does not provide an argument for this parameter when calling the function, the default value will be used. Parameters with default values must always follow parameters without default values.
*args: Variable Number of Positional Arguments
If you want your function to accept any number of positional arguments, you can use `*args`. Inside the function, `args` will be a tuple containing all the extra positional arguments provided.
**kwargs: Variable Number of Keyword Arguments
Similarly, `**kwargs` allows your function to accept any number of keyword arguments. Inside the function, `kwargs` will be a dictionary containing all the extra keyword arguments.
# Example of a default value
def welcome_user(name, city="Athens"):
print(f"Welcome, {name} from {city}!")
welcome_user("Maria") # Uses the default city
welcome_user("John", "Thessaloniki") # Overrides the default
print("-" * 20)
# Example of *args
def sum_multiple_numbers(*numbers):
print(f"The *args arguments are the tuple: {numbers}")
return sum(numbers)
print(f"Sum: {sum_multiple_numbers(1, 2, 3, 4)}")
print("-" * 20)
# Example of **kwargs
def display_profile(**info):
print(f"The **kwargs arguments are the dictionary: {info}")
for key, value in info.items():
print(f" {key.capitalize()}: {value}")
display_profile(name="Antonis", age=40, profession="Teacher")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.