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

Contenido del Curso

Mastering Python: Annotations, Errors and Environment

Mastering Python: Annotations, Errors and Environment

1. Annotations
2. Function Arguments in Details
3. Error Handling
4. Virtual Environment

bookPositional 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:

12345
def user_data(name, surname): print("Name:", name) print("Surname:", surname) user_data("John", "Smith")
copy

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:

12345
def user_data(name, surname): print("Name:", name) print("Surname:", surname) user_data("Smith", "John")
copy

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:

12345
def user_data(name, surname): print("Name:", name) print("Surname:", surname) user_data("John", "Smith", "11 years old")
copy

Keyword Arguments

We can specify the position of an argument using the keyword (argument name) and the assignment (=) operator:

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

All positional arguments should be provided with values.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

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