Contenido del Curso
Python Functions Tutorial
Python Functions Tutorial
Optional Arguments
What happens if one of the positional arguments is not specified? Let's examine an 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 occurs when we forget 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')
However, there is an important rule when using optional arguments: they must be specified after all non-optional arguments. If this rule is not followed, an 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)
¡Gracias por tus comentarios!