12. elif statement

The elif statement is equivalent to writing else: if and is used to evaluate multiple conditions as in a nested if structure, with the advantage of not requiring successive indentations.

This is an example of the elif statement used to translate numerical notes to text:

nota = input('Introduce una nota: ')
nota = float(nota)

if nota < 5:
    print('Insuficiente')
elif nota < 6:
    print('Suficiente')
elif nota < 7:
    print('Bien')
elif nota < 9:
    print('Notable')
else:
    print('Sobresaliente')

Exercises

  1. Write a program that classifies an integer as positive, negative, or zero.

    Clue:

    num = input('Introduce un número:')
    num = int(num)
    
    if num ... :
    
  2. Write a program that translates the month of the year into the season to which that month belongs. The months of each season are:

    • Winter: 1, 2, 12
    • Spring: 3, 4, 5
    • Summer: 6, 7, 8
    • Fall: 9, 10, 11

    Clue:

    mes = input('Mes del año (en número):')
    mes = int(mes)
    
    if mes ... :
    
  3. Write a program that detects if a number is a valid note. To be a valid grade, it must be greater than or equal to 1 and less than or equal to 10. If it is very low or very high, the program will notify you of the error. If the note is valid, the program will write it on the screen.

  4. Prime numbers. Write a program that checks if a positive number between 1 and 10 is prime. If it is not prime, write by which number it is divisible:

    • The number 1 is not prime by definition.
    • The numbers 2, 3, 5 and 7 are prime.
    • The numbers 4, 6, 8 and 10 are divisible by 2. They are not prime.
    • The number 9 is divisible by 3. It is not prime.
    • Numbers greater than 10 should give an error because they are too large.