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.
add() uses default values for
- If you don’t pass a value for
b, a will be set to 0 and
- If you only pass one value to
add()in the function call, this value will be passed in
bwill 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:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.