Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Optional Arguments | Function Arguments in Details
Mastering Python: Annotations, Errors and Environment

book
Optional Arguments

The positional arguments are required to be filled in. However, you can assign a default value to the positional argument using the = operator:

def user_data(name="UnknownName", surname="UnknownSurname"):
print("Name:", name)
print("Surname:", surname)

user_data("John", "Smith")
user_data("John")
user_data()
1234567
def user_data(name="UnknownName", surname="UnknownSurname"): print("Name:", name) print("Surname:", surname) user_data("John", "Smith") user_data("John") user_data()
copy

In the example above, if you don't pass a value to the name argument, it will be assigned the default value "UnknownName". The default value "UnknownSurname" and the surname argument work similarly.

The default value makes the corresponding positional arguments optional, but the total number of positional arguments required to be passed remains strict.

def user_data(name="UnknownName", surname="UnknownSurname"):
print("Name:", name)
print("Surname:", surname)

user_data("John", "Smith", "18 years old")
12345
def user_data(name="UnknownName", surname="UnknownSurname"): print("Name:", name) print("Surname:", surname) user_data("John", "Smith", "18 years old")
copy

In the next chapter, we will describe how to define a function that can take a variable number of arguments.

question mark

How many arguments the add() function requires to take?

def add(first, second=100):
return first + second

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 2

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt