19. Definition of functions

Functions are blocks of code that perform a certain task that we want to execute once or several times. Functions are also used to group instructions with a descriptive name.

Thanks to functions we can divide a long program into many small blocks. This makes it much easier for other people to program and read the code.

Example of a function definition and call:

def mensaje():            # Definición de la función
   print('Hola, mundo.')

mensaje()                 # Llamada a la función

The function definition does nothing by itself. The function message() needs to be called in order for the code inside it to be executed.

Parameters and arguments

Parameters are the variables that are declared between parentheses in the function definition.

The arguments are the values ​​we use to call the function. The arguments allow you to customize the behavior of a function and can be of different types (boolean, numbers, text strings, etc).

Example of defining a function with one parameter (name):

def saludo(nombre):
   print('Hola', nombre, '¿Qué tal estás?')

Function call with two different arguments ('Javier' and 'Sara'):

saludo('Javier')
saludo('Sara')

Result:

Hola Javier ¿Qué tal estás?
Hola Sara ¿Qué tal estás?

return statement

The return statement is used to return data from the function.

It can also be used to terminate the function at that point, with behavior similar to a break statement in a loop.

Example of a function definition with return:

def suma(a, b):
    return a + b

print(suma(3, 5))
print(suma(11, 23))

Result:

8
34

Exercises

  1. Write a function that calculates if a number is even or odd and prints the result to the screen.

    Also write multiple function calls with multiple numbers to the program to verify that it works correctly.

    Clue:

    def es_par(num):
        if num % 2 == 0:
           print(num, "es ...")
        else:
           print(num, "es ...")
    
  2. Write the definition of a function called 'maximum(a, b)' to which we pass two numbers as arguments and which returns the greater of the two.

    Also write several function calls with several pairs of numbers in the program to test that it works correctly.

    Clue:

    def mayor(a, b):
        if ... :
           return ...
        else:
           return ...
    
    print( mayor(5, 9) )
    print( mayor(20, 6) )
    print( mayor(12, 15) )
    

    Result:

    9
    20
    15
    
  3. Write the definition of a function that transforms degrees Celsius to degrees Fahrenheit knowing that:

    fahrenheit = celsius * 9.0 / 5 + 32
    

    Clue:

    def fahrenheit(celsius):
        return ...
    
    print("-5ºC =", fahrenheit(-5), "ºF")
    print("22ºC =", fahrenheit(22), "ºF")
    print("40ºC =", fahrenheit(40), "ºF")
    

    Result:

    -5ºC = 23.0 ºF
    22ºC = 71.6 ºF
    40ºC = 104.0 ºF
    
  4. Write the definition of a function that returns the factorial of a number.

    The factorial is the result of multiplying all the numbers from 1 to the desired number.

    Print the factorial of 5, 8, and 12.

    Clue:

    def factorial(num):
        resultado = 1
        while ... :
            resultado = ...
            num = num - 1
        return resultado
    
    print("El factorial de", ..., "es igual a", factorial( ... ))
    print("El factorial de", ..., "es igual a", factorial( ... ))
    print("El factorial de", ..., "es igual a", factorial( ... ))
    

    Result:

    El factorial de 5 es igual a 120
    El factorial de 8 es igual a 40320
    El factorial de 12 es igual a 479001600
    
  5. Write the definition of a function that prints a row of n asterisks to the screen.

    Call that function multiple times to print a triangle of asterisks starting with 1 asterisk and ending with 10 asterisks.

    Clue:

    def asteriscos(n):
        for i in range( ... ):
            print('*', end='')
        print()
    
    for num in range(1, 11):
        asteriscos( ... )
    
  6. Write the definition of a function that prints the multiplication table of a number.

    Use this function to print the table of 3 and the table of 5.

    Clue:

    def tabla_mult(n):
        print("Tabla del", ...)
        for i in range(1, 11):
            print( ... ,"x", ... , "=", ... )
    
    tabla_mult(3)
    tabla_mult(5)
    

    Result:

    Tabla del 3
    3 x 1 = 3
    3 x 2 = 6
    3 x 3 = 9
    3 x 4 = 12
    3 x 5 = 15
    3 x 6 = 18
    3 x 7 = 21
    3 x 8 = 24
    3 x 9 = 27
    3 x 10 = 30
    
    Tabla del 5
    5 x 1 = 5
    5 x 2 = 10
    5 x 3 = 15
    5 x 4 = 20
    5 x 5 = 25
    5 x 6 = 30
    5 x 7 = 35
    5 x 8 = 40
    5 x 9 = 45
    5 x 10 = 50