In Python, default parameter values provide a way to make function arguments optional. You can specify default values for one or more parameters when defining a function. If the caller doesn’t provide a value for a parameter with a default, the function will use the default value instead. This makes functions more flexible and reduces the need for the caller to specify every argument.
How to use default parameter values:
To set a default value for a parameter, assign the value directly in the function definition. Here’s the syntax:
def function_name(parameter=default_value):
# Function body
If the caller doesn’t pass a value for a parameter with a default, the function will use the default value. If a value is provided, it will override the default.
Example: simple greeting function
Let’s create a function that greets a user. The function will have a default parameter value for the greeting.
def greet_user(name, greeting="Hello"):
print(f"{greeting}, {name}!")
In this example:
has a default value ofgreeting .Hello
has no default value, so it’s required when calling the function.name
Calling the function:
Without specifying greeting
:
greeting
greet_user("Alice") # Output: Hello, Alice!
Here, greeting
Hello
Hello, Alice!
By specifying greeting
:
greet_user("Bob", greeting="Hi") # Output: Hi, Bob!
Here, we pass Hi
greeting
, overriding the default value.
Multiple default parameters:
You can define multiple default parameters. Let’s modify the function to allow a customizable punctuation mark.
def greet_user(name, greeting="Hello", punctuation="!"):
print(f"{greeting}, {name}{punctuation}")
Now:
defaults togreeting .Hello
defaults topunctuation .!
Calling the Function:
Using all defaults:
greet_user("Alice") # Output: Hello, Alice!
Overriding some defaults:
greet_user("Bob", greeting="Hi") # Output: Hi, Bob!
greet_user("Charlie", punctuation=".") # Output: Hello, Charlie.
greet_user("Diana", greeting="Hey", punctuation="?") # Output: Hey, Diana?
Important rules with default parameters
Rule 1: Default parameters must come after non-defaults
In a function definition, parameters with default values must appear after parameters without default values. This ensures clarity when arguments are assigned.
Incorrect:
def greet_user(greeting="Hello", name): # ❌ SyntaxError
# Function body
Correct:
def greet_user(name, greeting="Hello"): # ✔️
# Function body
Rule 2: Mutable default values caution
Be cautious when using mutable objects (like lists or dictionaries) as default parameter values, as they retain their state across multiple function calls. This can lead to unexpected behavior.
Example with mutable default values:
def add_to_list(item, my_list=[]):
my_list.append(item)
return my_list
print(add_to_list("apple")) # Output: ['apple']
print(add_to_list("banana")) # Output: ['apple', 'banana']
In this example, my_list
None
as the default and initialize the list inside the function:
def add_to_list(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
Summary:
- Default parameter values let you set a default for a parameter, making it optional for the caller.
- Order matters: Parameters with defaults must come after required parameters.
- Care with mutable defaults: Using mutable objects (e.g., lists, dictionaries) as default values can lead to unexpected behavior, as they retain their state between calls.
Default parameters add versatility to functions, allowing for simpler code that is more flexible by only requiring values when necessary.