Course Content
Python Functions Tutorial
Python Functions Tutorial
Optional Arguments
What will happen if one of the positional arguments is not specified? Let's look at the example:
# Function with two positional arguments def greet(name, age): print(f'Hello, {name}! You are {age} years old.') # Calling the `greet()` function with one missing argument greet(name='Alex')
An error occurred when we forgot to specify some of the positional arguments. In real projects, this behavior is unacceptable, as it generates many bugs and significantly impacts the system's fault tolerance. One approach to mitigate this issue is by employing default arguments.
These arguments are optional when calling the function, as the default value will be used if no value is specified for that argument.
To define an optional argument, you can assign a default value to the corresponding parameter in the function definition. Here's an example:
def greet(name, age=0): print(f'Hello, {name}! You are {age} years old.') # Calling the `greet()` function with missing optional argument greet(name='Alex')
But there is one important rule when using optional arguments - they must be specified after all non-optional arguments. If this rule is not met, the error will occur.
def greet(name='Alex', age): print(f'Hello, {name}! You are {age} years old.') # Calling the `greet()` function with optional argument before non-optional greet(age=35)
Thanks for your feedback!