Default Function Parameters in Python: How Can You Use Them?
--
Do you know that when you define a Python function you can set a default value for its parameters? This tutorial will show you how to do it.
Generally when calling a Python function you have to provide arguments for all the parameters defined in the function. When you use default parameters you give default values to specific parameters defined in a function. If a value is passed for that parameter when calling the function that value is assigned to the parameter otherwise the parameter keeps its default value.
In this tutorial we will first see how to use default parameters and then we will understand in which scenario you would use them.
Let’s see a few examples!
How to Add a Default Parameter to a Python Function
Before starting I want to remind you the difference between parameters and arguments.
Very often the difference between these two concepts is not very clear to developers…
Parameters are the variables listed in the definition of a Python function within parentheses. Arguments are the variables you pass when calling a function (again within parentheses). The values of arguments are assigned to the parameters of a function.
Let’s define a Python function that calculates the sum of two numbers.
def sum(a, b):
return a + b
When we call this function we have to pass two arguments:
print(sum(1, 2))
The output is:
$ python default_parameters.py
3
If you only pass one argument…
print(sum(1))
…you get the following error because the Python interpreter is expecting two arguments:
$ python default_parameters.py
Traceback (most recent call last):
File "default_parameters.py", line 4, in <module>
print(sum(1))
TypeError: sum() missing 1 required positional argument: 'b'
To set a default parameter in our function we use the equal sign followed by a value next to the parameter for which we want a default value.