Sub topic 5
Choosing among several cases with elif
This chapter assumes you can run Python scripts, know the basic types (int, str, list, dict, None), and have written a plain if/else statement. Here you will chain more than two cases with elif, trace which branch runs, and avoid the common errors.
The working model
elif is short for "else if". It adds another condition to an if statement. Python tests the conditions from top to bottom and runs the block of the first one that is True. It then skips the rest of the chain. If no condition is true, the optional else block runs.
score = 83
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
print(grade)This prints B. The check score >= 90 is false, so Python moves on. score >= 80 is true, so grade becomes 'B'. The score >= 70 test never runs, even though it is also true for 83.
Rules of the chain
- A chain starts with exactly one
if. It has any number ofelifclauses, then at most oneelse. - Each clause ends with a colon, and its block is indented.
elsehas no condition. It must come last.- Exactly one block runs, or none if there is no
elseand nothing matched.
Order matters
Because the first true condition wins, put the most specific tests first. This version is wrong:
score = 95
if score >= 70:
grade = 'C'
elif score >= 80:
grade = 'B'
elif score >= 90:
grade = 'A'
else:
grade = 'F'
print(grade)It prints C. The first test is true for 95, so the later tests never run. Order the tests from the strictest threshold to the loosest, as in the first example.
elif versus separate if statements
A series of separate if statements is not a chain. Python tests each one independently, so several blocks can run.
score = 95
if score >= 90:
print('A range')
if score >= 80:
print('B or better')This prints both lines. Changing the second if to elif would print only A range. Use elif when the cases are mutually exclusive. Use separate if statements when the checks are independent.
Common errors
- Writing
else if. Python has no such form. It is a syntax error. Useelif. - Putting a condition after
else.else score > 5:is a syntax error. Useelifinstead. - Overlapping conditions. Tests like
x > 5followed byx > 3look redundant but are fine. The danger is the reverse order, as shown above. - Misaligned indentation.
elifmust line up with itsif. If it is indented further, Python reports anIndentationErrororSyntaxError. - Forgetting the fallback. Without
else, a variable set inside the chain may stay undefined and raise aNameErrorlater. Add anelsethat sets a default, or set the default before the chain.
Exercise
What does this code print, and why? temp = 25 if temp > 30: print('hot') elif temp > 20: print('warm') elif temp > 10: print('mild') else: print('cold')
Show answer
It prints warm. The test temp > 30 is false. The test temp > 20 is true, so that block runs and Python skips the remaining clauses, including temp > 10, which would also be true.