12. and, or, not operators

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

Example to calculate if a year is a leap year:

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

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

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


  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.


    if (mes == 'abril') or (mes == 'mayo') or (mes == 'junio'):
  2. Write a program that uses the not operator to check if a number entered from the keyboard is odd.

  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('Sara')
    >>> len('Santiago')
  4. Write a program that answers that you have to turn on drip irrigation whenever it is night and it is not raining.


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

    Test the program with the four possible combinations on the sensors. What combinations cause irrigation to be connected?

  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.


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