Use Default Parameter Values
It is often useful to provide a default value for a parameter. If an argument for that parameter is not provided during the function call, the default value is used. This makes the parameter optional.
Let's see what happens when we call a function without a required argument. Open the default_params.py file and add the following code:
def hello(name):
print(f'Hello, {name}!')
hello()
Save the file and run it from the terminal:
python3 ~/project/default_params.py
This will produce a TypeError because the function hello was expecting one argument but received none.
Traceback (most recent call last):
File "/home/labex/project/default_params.py", line 4, in <module>
hello()
TypeError: hello() missing 1 required positional argument: 'name'
To fix this, we can assign a default value to the name parameter. Modify the default_params.py file by replacing its content with the following code:
def hello(name="World"):
print(f'Hello, {name}!')
hello()
hello("Jobs")
Now, run the script again:
python3 ~/project/default_params.py
The output will be:
Hello, World!
Hello, Jobs!
The first call uses the default value "World", while the second call uses the provided argument "Jobs".
Important Rule: In a function definition, all parameters without default values must come before any parameters with default values. For example, def func(a, b="default") is correct, but def func(a="default", b) will cause a SyntaxError.