Python elif statement: syntax, examples, and pitfalls
Learn how the python elif statement works, how to chain conditions, avoid common mistakes, and know when to replace long elif chains with more maintainable structures.
The Core Syntax of the python elif Statement
The elif keyword in Python provides a way to check multiple conditions sequentially. It is used between an if block and an optional else block. The general form is:
if first_condition: # executed when first_condition is True elif second_condition: # executed when first_condition is False and second_condition is True elif third_condition: # executed when the previous conditions are False and third_condition is True else: # executed when none of the above conditions are True
Only one block runs: the first condition that evaluates to True. If no condition is True, the else block runs if it exists. The elif clause can be repeated as many times as needed, and the else clause is optional.
How elif Differs from Nested if Statements
A common alternative is to nest if statements inside an else block:
if x > 0: result = "positive" else: if x < 0: result = "negative" else: result = "zero"
The elif version is flatter and easier to read:
if x > 0: result = "positive" elif x < 0: result = "negative" else: result = "zero"
The two are functionally equivalent, but elif reduces indentation and makes the control flow explicit. Nested if statements become difficult to follow when there are more than two or three branches.
Chaining Multiple elif Branches
You can chain as many elif clauses as you need. Python evaluates the conditions from top to bottom and stops at the first True condition. This is important because it means later conditions are not evaluated if an earlier one already matched.
def categorize(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "F"
In this example, a score of 95 returns "A" and the later comparisons are never executed. The order of the conditions matters: if you placed score >= 60 first, every score above 60 would return "D".
Common Mistakes with elif
The most frequent mistake is using the wrong indentation or forgetting the colon after the condition. Another common error is placing an else before an elif, which is syntactically invalid.
if x > 0: print("positive") else: print("non-positive") elif x < 0: # SyntaxError print("negative")
The elif must always follow an if or another elif, never an else. Also, conditions are evaluated in order, so overlapping conditions should be arranged deliberately to avoid unreachable branches.
Performance and Short-Circuit Evaluation
Because elif chains are evaluated sequentially, the number of comparisons performed depends on where the matching condition appears. In the worst case, all conditions are evaluated. This is rarely a performance problem unless the conditions themselves are expensive, such as database queries or complex function calls.
If you have many branches and each condition is costly, consider restructuring. For example, a dictionary mapping can replace a long elif chain when the conditions are simple equality checks.
def get_color_name(code): colors = {1: "red", 2: "green", 3: "blue"} return colors.get(code, "unknown")
This approach uses constant-time lookup and is often more maintainable than a chain of elif code == 1, elif code == 2, and so on.
Maintainability: When to Avoid Long elif Chains
Long elif chains become hard to read and modify. If you find yourself writing more than five or six branches, consider whether a data structure could express the logic more clearly. For range-based conditions, a list of tuples can work:
def grade(score): thresholds = [(90, "A"), (80, "B"), (70, "C"), (60, "D")] for limit, letter in thresholds: if score >= limit: return letter return "F"
This keeps the thresholds in one place and makes it easier to update them. For complex conditions that cannot be reduced to data, elif is still appropriate, but the conditions should be simple and readable.
elif and Python's match Statement
Python 3.10 introduced match for structural pattern matching. For simple value comparisons, match can sometimes replace an elif chain:
match command: case "start": start_service() case "stop": stop_service() case _: handle_unknown(command)
However, match is not a direct replacement for elif because it performs pattern matching, not arbitrary boolean evaluation. Use elif when you need to evaluate arbitrary expressions, and use match when you are matching against patterns or literal values.