How to Define a Function with Default Arguments in Python?

Default arguments allow you to define a function with optional arguments in Python. When calling the function, you can set the arguments—but you don’t have to. You set the default argument using the equal symbol = after the argument name and append the default value after that. Default arguments are a great Pythonic way to create reusable and concise code.

Here’s an example:

def add(a=0, b=1):
    return a + b
    

print(add(add(add())))
# 3

In the example, we specify a default value for function parameters. If there is no value passed to the parameter in the function call, the parameter will contain its default value.

The function add() uses default values for a and b.

  • If you don’t pass a value for a and b, a will be set to 0 and b to 1.
  • If you only pass one value to add() in the function call, this value will be passed in a and b will have its default value 1. Therefore the first call of add() returns 1. This is passed to add() again and therefore incremented by 1 and then again by 1.

Therefore this is what happens, step by step:

 add(add(add()))
 = add(add(1))
 = add(2)
 = 3

Now, that you understood this example, let’s do some practice testing!

Exercise: Guess the output. Run the code. Were you correct?

Where to Go From Here?

Understanding the Python basics is critical for your success in coding. Join my free Python email course and download the high-resolution Python cheat sheets to accelerate your training progress:

Leave a Comment