The order of conditions
Python checks the branches of a conditional statement from top to bottom and runs only the first one whose condition is true. That makes the order of the conditions important. This program should praise a great result, but it never does:
points = 95
if points >= 50:
print("Passed")
elif points >= 90:
print("Passed with distinction")
else:
print("Failed")
Passed95 is at least 50, so the first branch runs and the rest of the statement is skipped. In fact the elif points >= 90 branch can never run: every number that is 90 or more is also 50 or more, so the first condition always catches it first. The fix is to check the stricter condition first:
points = 95
if points >= 90:
print("Passed with distinction")
elif points >= 50:
print("Passed")
else:
print("Failed")
Passed with distinctionA good rule for limits like these: with >= or >, check the limits from the highest down; with <= or <, from the lowest up.
Each branch knows what came before
When Python gets to elif points >= 50, it already knows that points >= 90 was false. So that branch is really for points from 50 to 89, without having to say so. You don't need to repeat the earlier conditions in the later ones.
One statement or several
A chain of if, elif and else is one statement, and at most one of its branches runs. Separate if statements are each checked on their own, so several of them can run:
speed = 85
if speed > 80:
print("Fine: 200 euros")
if speed > 60:
print("Fine: 100 euros")
Fine: 200 euros
Fine: 100 eurosThe driver gets two fines. Change the second if into elif, and only the first one is printed. Use separate if statements when the checks have nothing to do with each other, and one chain when exactly one of the results should come out.