Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Optional Arguments | Positional and Optional Arguments
Python Functions Tutorial
course content

Contenido del Curso

Python Functions Tutorial

Python Functions Tutorial

1. What is Function in Python?
2. Positional and Optional Arguments
3. Arbitrary Arguments
4. Function Return Value Specification
5. Recursion and Lambda Functions

Optional Arguments

What will happen if one of the positional arguments is not specified? Let's look at the example:

123456
# 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')
copy

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:

12345
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')
copy

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.

12345
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)
copy

What happens if a function has both optional and non-optional arguments?

Selecciona la respuesta correcta

¿Todo estuvo claro?

Sección 2. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt