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

Course Content

Python Functions Tutorial

Python Functions Tutorial

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

book
Optional Arguments

What happens if one of the positional arguments is not specified? Let's examine an 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 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:

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

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.

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?

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

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt