10. and, or, not operators

These operators are used to make more complex conditions in an if statement.

Example to calculate whether a person can ride a roller coaster. They can only ride if their height in centimeters is greater than or equal to 150 and also less than or equal to 200:

altura = input('Escribe tu altura en centímetros: ')
altura = int(altura)

if (altura >= 150) and (altura <= 200):
    print('Puedes pasar')
else:
    print('No puedes pasar')

Example to calculate if a year is a leap year:

year = input('Escribe un año: ')
year = int(year)

if (year % 4 == 0) and ( (year % 100 != 0) or (year % 400 == 0) ):
    print(year, 'es bisiesto')
else:
    print(year, 'no es bisiesto')

Although parentheses are not always mandatory, it is advisable to use them so that the code can be better understood.

The not operator is used to check that the condition that follows it is false. It reverses the meaning of a condition.

Example of using the not operator:

num = input('Escribe un número del 1 al 10: ')
num = int(num)

if not (num % 2 == 0):
    print("El número", num, "NO es par")

Exercises

  1. Write a program that asks for the name of the month we are in and checks whether it is spring or not.

    To simplify we will say that April, May and June are the spring months.

    Clue:

    mes = input('Escribe el nombre de un mes: ')
    if (mes == 'abril') or (mes == 'mayo') or (mes == 'junio'):
       print('...')
    else:
       print('...')
    
  2. The following program checks whether a number is even. Modify the program using the not operator to check whether the number is odd:

    num = input('Escribe un número: ')
    num = int(num)
    
    if (num % 2 == 0):
        print('El número es par')
    
  3. Write a program that uses the and operator to check if a name is between 4 and 6 letters long.

    The length of a text string is measured with the len() function.

    >>> len('Ana')
        3
    >>> len('Gustavo')
        7
    

    Clue:

    nombre = input('Escribe un nombre: ')
    letras = len(nombre)
    
    if ... :
        print('El nombre tiene entre 4 y 6 letras')
    
  4. Write a program that responds that you have to turn on drip irrigation whenever it is nighttime (not daytime) and the soil is dry (it is not raining).

    Clue:

    sensor_lluvia = 1
    sensor_de_dia = 0
    
    if ... :
        print('Conecta el riego por goteo.')
    else:
        print('Desconecta el riego por goteo.')
    

    Test the program with the four possible sensor combinations. It should only work when the rain sensor is zero and the day sensor is zero.

  5. Write a program that prints a message when a number is positive, even, and not divisible by 3. Otherwise, it does not print any message.

    Clue:

    num = input('Escribe un número:')
    num = int(num)
    
    if ... :
       print(num, 'es positivo y no es divisible por 3.')