Both at once: and
Sometimes one condition isn't enough. A roller coaster might let you ride only if you are at least 10 years old and also at least 140 cm tall. The logical operator and combines two conditions into one, which is true only when both of them are true:
age = int(input("Age: "))
height = int(input("Height in cm: "))
if age >= 10 and height >= 140:
print("Enjoy the ride!")
else:
print("Sorry, you can't ride yet.")
12
135Age: 12
Height in cm: 135
Sorry, you can't ride yet.The rider is old enough but not tall enough, so the whole condition is false. The interpreter shows all four combinations:
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
FalseOnly True and True gives True. You can also join more than two conditions: a and b and c is true only when all three are.
Between two limits
The most common use of and is to check that a number is in a range. Here hour >= 9 and hour < 17 is true for the hours 9 to 16:
hour = int(input("Hour (0 to 23): "))
if hour >= 9 and hour < 17:
print("The shop is open.")
else:
print("The shop is closed.")
18Hour (0 to 23): 18
The shop is closed.Each side is a whole condition
In English you could say "if the hour is at least 9 and less than 17", and leave out the second "the hour". Python can't fill in the missing part:
hour = 10
if hour >= 9 and < 17:
print("The shop is open.")
File "main.py", line 2
if hour >= 9 and < 17:
^
SyntaxError: invalid syntaxAfter and, Python expects a whole new condition, but it finds <. Write the variable again: hour >= 9 and hour < 17.