Ranges and longer conditions
Checking that a value is between two limits is so common that Python has a shorter way to write it. Instead of grade >= 4 and grade <= 10, you can write 4 <= grade <= 10, as in mathematics:
grade = int(input("Grade (4 to 10): "))
if 4 <= grade <= 10:
print("Grade saved.")
else:
print("That's not a valid grade.")
11Grade (4 to 10): 11
That's not a valid grade.This is called a chained comparison. Python reads 4 <= grade <= 10 as 4 <= grade and grade <= 10, so the value in the middle is compared with both limits. Any comparison operators can be chained:
>>> x = 7
>>> 0 < x < 10
True
>>> 1 <= x <= 5
False
>>> a = 3
>>> b = 3
>>> a == b == 3
TrueThe two ways mean exactly the same, and you'll meet both in Python code. The chained one is shorter, and it shows the variable between its two limits, the way you'd write it in a math class.
Longer conditions
A condition can combine as many parts as it needs, and conditions with and and or work in an elif like anywhere else. In this quiz game, a player who scores at least 90 points within 60 seconds wins gold, a player who manages one of the two wins silver, and 50 points are enough for bronze:
points = int(input("Points: "))
seconds = int(input("Time in seconds: "))
if points >= 90 and seconds <= 60:
print("Gold medal")
elif points >= 90 or seconds <= 60:
print("Silver medal")
elif points >= 50:
print("Bronze medal")
else:
print("No medal this time")
95
75Points: 95
Time in seconds: 75
Silver medalNotice the order. The and condition comes first, because it is the strictest one: it needs both parts. A result that has both parts also has at least one of them, so if the or condition came first, it would catch every gold result too, and nobody would ever win gold. The order of conditions matters just as much with and and or as without them.