Sub topic 5
Choosing among several cases with elif
This chapter assumes you can run Python scripts, know the basic data types (int, float, str, bool, list, dict, None), and can define a simple function. It also assumes you have read the earlier chapters on if and else.
Why elif exists
An if/else pair chooses between two blocks. Many decisions have more than two outcomes, such as converting a numeric score to a letter grade. You could nest an if inside each else, but the code drifts to the right with every added case. The elif clause (short for "else if") adds more cases at the same indentation level.
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 working model: one chain, one winner
An if, its elif clauses, and its optional else form a single decision chain. Python evaluates it like this:
- Test the
ifcondition. If it is truthy, run its block and skip the rest of the chain. - Otherwise test the first
elifcondition, then the next, in the order written. - Run the block of the first condition that is truthy, then leave the chain.
- If no condition is truthy, run the
elseblock when there is one. If there is noelse, run nothing.
At most one block runs. Conditions after the winning one are never evaluated.
Order matters
Because the first true condition wins, the order of your tests decides the result. In the grade example, a score of 95 satisfies score >= 90, score >= 80, and score >= 70. It gets an A only because the >= 90 test comes first.
Here is the same chain with the tests in the wrong order:
score = 95
if score >= 70:
grade = 'C'
elif score >= 80:
grade = 'B'
elif score >= 90:
grade = 'A'
else:
grade = 'F'
print(grade)This prints C. The first test is true for 95, so Python never looks at the others. No error is raised. The program simply gives a wrong answer, which makes this bug easy to miss.
When conditions overlap like this, put the most specific or most restrictive test first. When the conditions are mutually exclusive (for example status == 'new' and status == 'done'), the order does not affect correctness, and you can order them by readability or by how often each is true.
Ranges let earlier tests do the work
The grade chain never writes score >= 80 and score < 90 for the B case. It does not need to. By the time Python reaches the elif score >= 80 test, the score >= 90 test has already failed, so the score must be below 90. Each elif implicitly carries the negation of every test above it.
This keeps conditions short, but it ties each test to its position. If you reorder the chain or insert a new case in the middle, you must re-check that the implicit assumptions still hold.
elif versus a series of separate if statements
A chain is not the same as several independent if statements. Compare these two versions:
n = 15
# Version 1: one chain
if n % 3 == 0:
print('divisible by 3')
elif n % 5 == 0:
print('divisible by 5')
# Version 2: two separate statements
if n % 3 == 0:
print('divisible by 3')
if n % 5 == 0:
print('divisible by 5')Since 15 is divisible by both numbers, Version 1 prints only divisible by 3. Version 2 prints both lines, because each if starts a fresh test.
Use a chain when the cases are alternatives and exactly one outcome should apply. Use separate if statements when the checks are independent and several may apply at once.
The else clause is optional
An elif chain does not need a final else. Without one, a value that matches nothing falls through and the chain does nothing.
That can be intended, but it can also leave a variable unassigned:
temperature = 25
if temperature < 0:
state = 'freezing'
elif temperature < 15:
state = 'cold'
elif temperature < 20:
state = 'mild'
print(state)For 25, no condition is true, so state is never assigned. The print line raises NameError: name 'state' is not defined. If this code ran earlier with a different value of state in scope, you would instead get a stale value, which is worse.
There are two common fixes. You can add an else that assigns a default, or you can assign a default before the chain.
temperature = 25
if temperature < 0:
state = 'freezing'
elif temperature < 15:
state = 'cold'
elif temperature < 20:
state = 'mild'
else:
state = 'warm'
print(state)Using else to catch the unexpected
When the cases should cover every valid input, use the final else to reject anything else. This turns a silent bug into a visible error.
def day_type(day):
if day in ('Sat', 'Sun'):
return 'weekend'
elif day in ('Mon', 'Tue', 'Wed', 'Thu', 'Fri'):
return 'weekday'
else:
raise ValueError(f'unknown day: {day!r}')
print(day_type('Sun'))
print(day_type('Wed'))This prints weekend and then weekday. Calling day_type('Funday') raises ValueError: unknown day: 'Funday'.
Conditions in an elif can be any expression
Each elif takes the same kind of condition as an if. That includes comparisons, and/or/not, membership tests, and plain truthy values. The conditions in a single chain do not have to test the same variable.
def classify(user, balance):
if user is None:
return 'anonymous'
elif balance < 0:
return 'overdrawn'
elif not user:
return 'empty name'
elif balance == 0:
return 'zero balance'
else:
return 'ok'
print(classify(None, 10))
print(classify('ana', -5))
print(classify('', 10))
print(classify('ana', 0))
print(classify('ana', 10))The output is, in order: anonymous, overdrawn, empty name, zero balance, ok. This works, but a chain that mixes many unrelated variables is harder to reason about. If the tests are no longer about one idea, consider splitting the function or using guard clauses (covered in a later chapter).
Side effects in conditions
Python stops evaluating a chain at the first true condition. If a condition calls a function with side effects, such as reading input or writing a log line, later conditions will not run it. Keep conditions free of side effects, or compute the value once before the chain:
reply = input('Continue? ').strip().lower()
if reply in ('y', 'yes'):
print('continuing')
elif reply in ('n', 'no'):
print('stopping')
else:
print('please answer yes or no')Here input() runs once, and each branch tests the stored result. Calling input() inside each condition would ask the user a new question at every step.
Common mistakes with elif
| Mistake | What happens | Fix |
|---|---|---|
| Writing `else if` | `SyntaxError` | Use the single keyword `elif` |
| Missing colon after the condition | `SyntaxError: expected ':'` | End every `if`, `elif`, and `else` line with `:` |
| Using `=` in a condition | `SyntaxError` | Use `==` to compare |
| Giving `else` a condition | `SyntaxError` | Use `elif` if a condition is needed |
| Placing `elif` after `else` | `SyntaxError` | `else` must be last in the chain |
| Misaligned `elif` | Wrong structure or `IndentationError` | Align `elif` and `else` exactly with their `if` |
| Broader test placed first | Later branches never run | Put specific tests before general ones |
| Using `if` where `elif` was meant | Several blocks run | Use `elif` for mutually exclusive cases |
The alignment error deserves an example. If an elif is indented deeper than its if, it no longer belongs to that chain:
x = 5
if x > 10:
print('big')
elif x > 3:
print('medium')Python rejects this code with an IndentationError or SyntaxError before running anything, because an elif indented under the if body has no if to attach to. Always line up if, elif, and else at the same column.
When a chain gets long
A chain of five or ten elif clauses is legal, but it is a signal to look for a simpler shape. Python checks conditions one at a time, so a very long chain is also slower in the worst case, though readability is the usual concern, not speed.
- If every branch compares one value to a constant, a
matchstatement (Python 3.10 and later) can express the same thing more clearly. A later chapter covers it. - If every branch only returns a different value for a different key, a dictionary lookup is shorter. For example,
{'Sat': 'weekend', 'Sun': 'weekend'}.get(day, 'weekday'). - If each branch runs different logic, consider moving each branch into a named function so the chain reads as a short list of decisions.
Exercises
Exercise
What does this code print, and why? n = 12 if n > 5: print('A') elif n > 10: print('B') else: print('C')
Show answer
It prints A. The first condition n > 5 is true, so Python runs that block and skips the rest of the chain. The elif n > 10 test is never evaluated, even though it is also true. To make B reachable for values above 10, the n > 10 test must come before n > 5.
Exercise
Write a function ticket_price(age) that returns 0 for ages under 5, 8 for ages 5 to 17, 15 for ages 18 to 64, and 10 for ages 65 and over. Raise ValueError for a negative age.
Show answer
One solution: def ticket_price(age): if age < 0: raise ValueError('age cannot be negative') elif age < 5: return 0 elif age < 18: return 8 elif age < 65: return 15 else: return 10 Each elif relies on the earlier tests having failed, so no test needs a lower bound. For example, reaching age < 18 means age is already 5 or more.
Exercise
A student writes two separate if statements instead of if/elif to assign 'low', 'medium', or 'high' to a variable level based on a value v: if v < 10, level = 'low'; if v < 20, level = 'medium'; else level = 'high'. What goes wrong for v = 3?
Show answer
The first if sets level to 'low'. The second statement is a new if/else, and since 3 < 20 is true, it overwrites level with 'medium'. The final result is 'medium' instead of 'low'. Changing the second if to elif makes the three cases one chain, so only the first matching block runs.