10. and
, or
, not
operators¶
These operators are used to make more complex conditions in an if
statement.
Ejemplo para calcular si una persona puede subir a una montaña rusa. Solo podrá subir si su altura en centímetros es mayor o igual a 150 y también debe ser menor o igual a 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.
Exercises¶
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('...')
El siguiente programa comprueba si un número es par. Modifica el programa utilizando el operador
not
para que compruebe si el número es impar:num = input('Escribe un número: ') num = int(num) if (num % 2 == 0): print('El número es par')
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')
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.
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.')