Blog Post #89: Making Arguments Optional with Default Parameter Values

In Post #87 and Post #88, we learned how to pass information to our functions using positional and keyword arguments. In all of our examples so far, every parameter we defined was required. If we defined a function with two parameters, we had to call it with two arguments, or the program would crash.

But what if you want a parameter to be optional? What if a value is so common that you’d like to provide a default for it, but still allow it to be changed? In this post, we will learn how to set default parameter values to make our functions more flexible.

What is a Default Parameter Value?

A default parameter value is a value that you assign to a parameter directly in the function definition using the = assignment operator.

When the function is called:

  • If an argument is provided for that parameter, the default value is ignored and the provided argument is used.
  • If an argument is not provided for that parameter, the default value is used automatically.

This effectively makes the argument optional for the person calling the function.

Default Values in Action

Let’s modify our describe_pet function. Let’s assume that most of the pets we’ll be describing are dogs. We can make “dog” the default value for the animal_type parameter.

The Function Definition

We add = "dog" right after the animal_type parameter in the def statement.

def describe_pet(pet_name, animal_type="dog"):
    """Displays information about a pet."""
    print(f"\nI have a {animal_type}.")
    print(f"Its name is {pet_name}.")

Calling the Function

Now we have two ways to call this function.

Case 1: Overriding the Default

If we want to describe a different kind of animal, we can still provide the animal_type argument as usual. The value we pass will override the default value.

# Using a positional argument to override the default
describe_pet("Harry", "hamster")

# Using a keyword argument to override the default
describe_pet(pet_name="Whiskers", animal_type="cat")

Case 2: Using the Default

Now, if we want to describe a dog, we can simply omit the animal_type argument. Python will see that it’s missing and automatically use the default value “dog”.

# We only need to provide the required argument, 'pet_name'
describe_pet("Fido")

Running all three calls produces the following flexible output:

I have a hamster.
Its name is Harry.

I have a cat.
Its name is Whiskers.

I have a dog.
Its name is Fido.

An Important Syntax Rule

When you define a function, there is one critical rule you must follow when using default parameter values:

All parameters with default values must be listed after all parameters that do not have default values.

# VALID: Required parameters first, then optional ones.
def create_user(username, is_admin=False):
    # ... function code ...
    pass

# INVALID: This will cause a SyntaxError!
# def create_user(is_admin=False, username):
#     # ... function code ...
#     pass

This rule exists to avoid ambiguity. It ensures that when you call a function with positional arguments, Python knows exactly which required parameters they map to.

What’s Next?

Default parameter values make your functions much more flexible. They allow you to define required information while making common or less critical information optional, leading to cleaner and simpler function calls.

Using default values like strings, numbers, or True/False is safe and straightforward. However, there is a major and infamous pitfall when you use a mutable type, like a list, as a default value. This can lead to some of the most confusing bugs for new Python programmers. In Post #90, we will investigate this “mutable default argument” pitfall and learn how to avoid it.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment