Language: EN

python-parametros-funcion

Function Parameters and Arguments in Python

The parameters of a function are variables that we can pass to the function when invoking it, for it to use. Parameters allow functions to be more flexible and reusable.

The basic syntax for defining a function with parameters in Python is as follows:

def function_name(parameter1, parameter2, ...):
    # code block of the function that uses the parameters
  • parameter1, parameter2,… are the parameters of the function

Let’s see an example:

def greet(name):
    print("Hello", name)

# Calling the function with an argument
greet("Luis")  # Output: Hello Luis

Here we define a function called greet that takes a parameter called name. Inside the function, a greeting “Hello” followed by the name passed as an argument is printed.

Now, if I call the function with the parameter Luis, this causes the function to execute and display the message “Hello Luis” as output.

Types of parameters in Python

Positional Parameters

Positional parameters are the most common parameters. They are defined in the order they appear in the function’s parameter list and are passed to the function in the same order.

def add(a, b):
    result = a + b
    return result

# Calling the function with positional parameters
result_addition = add(5, 3)
print(result_addition)  # Output: 8

Parameters with Default Values

Parameters with default values are parameters that have a default value assigned in the function definition.

def greet(name="World"):
    print("Hello,", name)

# Calling the function without providing a value for the parameter
greet()  # Output: Hello, World

# Calling the function with a value for the parameter
greet("Luis")  # Output: Hello, Luis

If no value is provided for these parameters when calling the function, the default value will be used.

Named Parameters

Named parameters are parameters that are passed to the function using their name (instead of their position).

This allows changing the order of the parameters or even omitting some of them.

def greet(name, greeting="Hello"):
    print(greeting + ",", name)

# Calling the function with named parameters
greet(name="Ana")  # Output: Hello, Ana
greet(greeting="Good morning", name="Pedro")  # Output: Good morning, Pedro

Variable Length Parameters

Python allows defining functions that accept a variable number of parameters using *args and **kwargs.

  • *args: Used to pass a list of positional arguments
def add_numbers(*args):
    result = sum(args)
    return result

# Calling the function with a variable number of arguments
result_addition = add_numbers(1, 2, 3, 4, 5)
print(result_addition)  # Output: 15
  • **kwargs: Used to pass a dictionary of keyword arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(key + ":", value)

# Calling the function with named arguments
print_info(name="Luis", age=30, city="Madrid")
# Output:
# name: Luis
# age: 30
# city: Madrid

Using * and ** when calling a function Advanced

When we have a list or dictionary and want to pass its elements as arguments to a function, we can use * and ** respectively.

  • The operator * is used when we want to unpack the elements of a list and pass them as arguments to a function.
def sum(a, b, c):
    return a + b + c

values = [1, 2, 3]
print(sum(*values))  # Result: 6

Here,

  • values is a list containing [1, 2, 3]
  • When calling sum(*values), the elements of the list are unpacked and passed as arguments to the sum function
  • That is, it is equivalent to calling sum(1, 2, 3)

The operator ** is used similarly, but to unpack the elements of a dictionary and pass them as arguments to a function.

In this case, the keys of the dictionary become parameter names and the values of the dictionary are assigned to those parameters.

dictionary = {"a": 1, "b": 2, "c": 3}
print(sum(**dictionary))  # Result: 6

Here,

  • dictionary is a dictionary containing {"a": 1, "b": 2, "c": 3}
  • When calling sum(**dictionary), the elements of the dictionary are unpacked and passed as arguments to the sum function,
  • The key "a" is assigned to parameter a, the key "b" is assigned to b, and the key "c" is assigned to c
  • That is, it is equivalent to calling sum(a=1, b=2, c=3)

Pass by Value or by Reference

In Python, passing arguments to functions is always done by value (that is, the function always receives a copy of the argument).

But the behavior will be different if what we pass is a basic type or a reference.

  • In a basic type, the invoked function will not be able to modify the argument it receives
  • In a reference type, it will be able to modify the argument it receives.

Let’s see this with an example. First, let’s see the behavior when we pass a basic type. For example, we pass an integer (int) to the function modify_number().

Inside the function, we multiply the number by 2. This modification does not affect the original number outside the function.

# Example with a basic type (int)
def modify_number(number):
    number = number * 2

original_number = 5
modify_number(original_number)
print("Original number after calling the function:", original_number)  # Result: 5

Now let’s see what happens with a reference type, for example a list that we pass by reference to the function modify_list().

Inside the function, we add the number 4 to the list. The modification made inside the function is reflected in the original list outside the function.

# Example with a reference (list)
def modify_list(lst):
    lst.append(4)

original_list = [1, 2, 3]
modify_list(original_list)
print("Original list after calling the function:", original_list)  # Result: [1, 2, 3, 4]