Python default parameters
Created By: chatGPT
In Python, default parameters allow you to define a function with parameters that have default values. This means that if a function is called without providing a specific argument for that parameter, Python will use the default value instead.
def greet(name='Guest'):
return f'Hello, {name}!'
# Calling the function without an argument
print(greet()) # Output: Hello, Guest!
# Calling the function with a specific argument
print(greet('Alice')) # Output: Hello, Alice!
Default parameters can also be achieved with multiple parameters. If you use several parameters with default values, only the ones that are omitted will take those defaults.
def introduce(name, age=25, city='Unknown'):
return f'Name: {name}, Age: {age}, City: {city}'
# Only providing the required argument
print(introduce('Bob')) # Output: Name: Bob, Age: 25, City: Unknown
# Providing all arguments
print(introduce('Carol', 30, 'New York')) # Output: Name: Carol, Age: 30, City: New York
It's essential to keep in mind that default mutable arguments can lead to unexpected behavior. If a mutable object (like a list or dictionary) is used as a default value, it is shared across all calls to the function. This could cause state issues.
def add_item(item, item_list=[]):
item_list.append(item)
return item_list
# Calling the function multiple times
print(add_item('apple')) # Output: ['apple']
print(add_item('banana')) # Output: ['apple', 'banana']
# To avoid this behavior, it's better to use None as a default value:
def add_item_fixed(item, item_list=None):
if item_list is None:
item_list = []
item_list.append(item)
return item_list