Conteúdo do Curso
Mastering Python: Annotations, Errors and Environment
Mastering Python: Annotations, Errors and Environment
Positional Arguments
In beginner courses, you may have learned how to work with functions. Let's dive deeper into the capabilities of functions.
Functions can have different types of arguments. Let's describe each type.
Types of Arguments
- Positional arguments
- Optional arguments
- Arbitrary Arguments
- Keyword arguments
Let's start with regular arguments that are widely used.
Positional Arguments
The positional arguments have a position inside the function code:
The argument1
and argument2
are positional arguments.
When you call the function and pass the values, they are placed according to their position:
def user_data(name, surname): print("Name:", name) print("Surname:", surname) user_data("John", "Smith")
The "John"
string is a first taken value that assigns to the first positional argument name
. The Smith
is assigned to the surname
as the second positional argument.
The order and number of positional arguments are strict, meaning that the values passed to the function must be provided in the correct order and number for each positional argument:
def user_data(name, surname): print("Name:", name) print("Surname:", surname) user_data("Smith", "John")
In the example above, the "Smith"
is assigned to the name
argument, and the "John"
is assigned to the surname
argument. It's a mistake.
What about the number of positional arguments? If we pass the wrong number of arguments, the interpreter will raise an error:
def user_data(name, surname): print("Name:", name) print("Surname:", surname) user_data("John", "Smith", "11 years old")
Keyword Arguments
We can specify the position of an argument using the keyword (argument name) and the assignment (=
) operator:
def user_data(name, surname): print("Name:", name) print("Surname:", surname) user_data(surname="Smith", name="John")
All positional arguments should be provided with values.
Obrigado pelo seu feedback!