Language: EN

python-funciones

Functions in Python

Functions are blocks of code that perform a specific task and can be reused in different parts of a program.

Functions allow us to structure our code in a more organized, modular, and easy-to-maintain way.

Defining a function

In Python, a function is defined with the def keyword, followed by the name of the function and parentheses that can contain the input parameters.

The basic syntax of a function in Python is as follows:

def function_name(parameters):
    # Function code block
    # Can contain multiple statements
    return result
  • function_name: Is the name we give to our function.
  • parameters: Are the parameters that our function can receive. These are optional and can be used to pass information to the function.
  • return result: The return statement allows us to return a result from the function. It is optional and can return any type of data.

Calling a function

Once a function has been defined, it can be called (or invoked) from any part of the program.

To call a function, you use its name followed by parentheses that can contain the arguments the function expects.

For example, if we have this function:

def greet():
    print("Hello Luis")

We can call it like this:

greet()

In this case, the greet function is called, which will display the message “Hello Luis”.

Parameters and arguments

Parameters are the variables defined in the function declaration. Parameters allow us to “give” data to a variable, making them much more flexible and reusable.

For example, imagine we have a function that simply adds two numbers. We can make it receive two parameters and perform the addition.

In this case, a and b are parameters of the sum function. We could have chosen any other name for a and b, the names are chosen by us.

def sum(a, b):
    print(a + b) # Output: 8

sum(3, 5) # We call the function

On the other hand, the arguments are the specific values that are passed to the function when we call it. In the example, 3 and 5 are the arguments passed when calling it.

Return values

Functions in Python can return a value using the return keyword. This value can be assigned to a variable when calling the function. For example:

def giveNumber()
    return 8;

result = giveNumber(8)
print(result) # Output: 8

For example, here the giveNumber() function returns 8.

Example of a simple function

If we combine the above, we can already make a very simple function that adds two numbers and returns the result:

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

In this example, the add function receives two parameters a and b, adds these values, and then returns the result. Now we can call this function and use it in our program:

sum_result = add(5, 3)
print("The result of the sum is:", sum_result)  # Output: The result of the sum is: 8