24. Default parameter values

Quiz: 0/5

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:

  • greeting has a default value of Hello.
  • name has no default value, so it’s required when calling the function.

Calling the function:

Without specifying greeting:

greet_user("Alice")  # Output: Hello, Alice!

Here, greeting uses its default value Hello, so the output is Hello, Alice!.

By specifying greeting:

greet_user("Bob", greeting="Hi")  # Output: Hi, Bob!

Here, we pass Hi for 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:

  • greeting defaults to Hello.
  • punctuation defaults to !.

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 retains its state between calls. To avoid this, use 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.

Hands-On Practise

Exercise: Customizing greetings

Create a function personalized_greeting that takes three parameters:

  1. name (required) – the name of the person you are greeting.
  2. greeting (optional) – the greeting message (defaults to "Hello").
  3. punctuation (optional) – punctuation at the end of the greeting (defaults to "!").

The function should print the personalized greeting using the provided arguments or default values.

Instructions:

  1. Function Definition:

    • Define the function personalized_greeting(name, greeting="Hello", punctuation="!").
    • Inside the function, print the greeting message formatted as:
      {greeting}, {name}{punctuation}.
  2. Function Calls:

    • Call the function without providing any optional parameters. It should use the default greeting Hello and punctuation !.
    • Call the function with only the greeting parameter. It should override the default greeting but use the default punctuation.
    • Call the function with both the greeting and punctuation parameters. It should override both defaults.
    • Call the function with no optional parameters but with a unique name.

Bonus challenge (Optional):

Modify the function to accept a list of names and print a greeting for each name in the list using the same greeting and punctuation. Make sure the function handles both single names and a list of names appropriately.

Output:

Quizzes: 0/5

Question 1:

What is the purpose of default parameter values in Python functions?

  • To make a parameter mandatory for the function to work.
  • To allow a function to be called without providing a value for certain parameters.
  • To assign a fixed value to every parameter in the function.
  • To define multiple parameters with the same default value.

Question 2:

Which of the following is true about default parameters in Python?

  • Default parameters must be placed before non-default parameters in the function definition.
  • Default parameters can only have immutable types as their default values.
  • Default parameters can be overridden when calling the function.
  • Default parameters cannot be used in functions with more than three parameters.

Question 3:

What happens if you pass a value for a default parameter when calling a function?

  • The default value is ignored, and the passed value is used instead.
  • The default value is used in place of the passed value.
  • An error occurs, and the function call is not executed.
  • The function will always use the default value, regardless of the passed value.

Question 4:

What is the correct way to define a function with default parameters in Python?

  • def function_name(parameter='default_value'):
  • def function_name(parameter, default_value='default'):
  • def function_name(parameter=default_value):
  • def function_name(default_value, parameter):

Question 5:

What is a potential issue when using mutable objects (like lists or dictionaries) as default parameters?

  • The function will not work at all if a mutable object is used.
  • The mutable object will retain its state across multiple function calls, leading to unexpected behavior.
  • Mutable objects cannot be used as default parameters in Python.
  • Mutable objects are automatically converted into immutable types when used as default parameters.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonUnderstanding positional and keyword argumentsNext lessonUnderstanding *args and **kwargs