20. Parameters with default values

Functions can have parameters, which are variables that are used inside the function. When calling the function we assign arguments (data) to the parameters of the function.

Parameters can have default values ​​and in that case you can omit the argument in the function call. These parameters with default values ​​must be placed to the right of the other parameters.

Example:

def saludo(nombre='María'):
    print('Te saludo,', nombre)

saludo()
saludo('Nerea')

Exit:

Te saludo, María
Te saludo, Nerea

As you can see, when we call the function without any arguments, the default value is used, which in this case is 'Mary'.

Exercises

  1. Write a function that counts the numbers divisible by the 'divisor' in all the numbers from 1 to the 'top' number.

    Clue:

    def multiplos(divisor, tope):
        contador = 0
        ...
    
    
    multiplos(3, 20)
    multiplos(5, 50)
    

    Exit:

    Hay 6 múltiplos de 3 desde el 1 hasta el 20
    Hay 10 múltiplos de 5 desde el 1 hasta el 50
    
  2. Modify the above function so that the last parameter has a default value of 100.

    Exit:

    >>> multiplos(7)
        Hay 14 múltiplos de 7 desde el 1 hasta el 100
    
  3. Write a function that counts the vowels in a string of text.

    Clue:

    def contar_vocales(cadena):
       vocales = 'aeiouAEIOUáéíóúÁÉÍÓÚ'
       contador = 0
       for letra in cadena:
          if letra in vocales:
             ...
    

    Exit:

    En la cadena " Este es un ejemplo de cadena de texto " hay 14 vocales.
    En la cadena " En un lugar de la Mancha, de cuyo nombre no quiero acordarme " hay 22 vocales.
    
  4. Write a function that prints the smallest of three numbers that we pass to it as arguments.

    Clue:

    def menor(a, b, c):
        print('Número menor:', end=' ')
        if a < b and a < c:
            print(a)
        ...
    
    
    menor(3, 1, 7)
    menor(10, 2, 5)
    menor(6, 12, 3)
    

    Exit:

    Número menor: 1
    Número menor: 2
    Número menor: 3
    
  5. Write a function that returns 'True' if three numbers that we pass to it as arguments are in order from least to greatest. Otherwise, it should return 'False'

    Clue:

     def ordenados(a, b, c):
         if a < b and b < c:
             ...
    
    ordenados(3, 1, 7)
    ordenados(5, 7, 10)
    

    Exit:

    False
    True
    
  6. Write a function that prints three numbers that we pass as arguments, after sorting them. Use the function from the previous exercise to find out if the numbers are sorted.

    Clue:

    def ordenar(a, b, c):
        print('Números ordenados:', end=' ')
        if ordenados(a, b, c):
            print(a, b, c)
        elif ordenados(a, c, b):
            print(a, c, b)
        ...
    
    ordenar(3, 7, 1)
    ordenar(10, 2, 5)
    ordenar(12, 6, 3)
    

    Exit:

    Números ordenados: 1 3 7
    Números ordenados: 2 5 10
    Números ordenados: 3 6 12