Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python if elif else: Syntax, Behavior, and Alternatives

Understand Python's if/elif/else chain: how conditions are evaluated, common mistakes, and when a dictionary mapping is a better choice.

~4 min readPython
#conditional statements#control flow#python syntax#elif
Diagram of Python if elif else branching logic with three decision paths and a final fallback.

The if/elif/else chain is the primary way to express conditional branching in Python. It evaluates conditions in order and executes the first block whose condition is true. Understanding exactly how this evaluation works matters because it affects both correctness and readability of your code.

Basic Syntax of If, Elif, and Else

The syntax is straightforward:

python
if condition1: # block 1 elif condition2: # block 2 else: # fallback

elif is short for "else if". You can include any number of elif blocks between if and else. The else block is optional and runs only when none of the preceding conditions are true. Each block must be indented consistently, typically with four spaces.

How Python Evaluates the Chain

Python evaluates the conditions from top to bottom. The first condition that evaluates to true triggers its block, and the rest of the chain is skipped. If no condition is true, the else block runs if it exists. This behavior is important when conditions have side effects: if a condition calls a function that modifies state, that function is not called when an earlier condition has already matched.

python
def expensive_check(): print("called") return True if False: pass elif expensive_check(): pass

In this example, expensive_check() is called because the first condition is false. If the first condition were true, the function would not be called at all.

Practical Example: Mapping a Score to a Grade

A common use case is converting a numeric score to a letter grade:

python
def grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "F"

The order of conditions is critical. Because each condition is checked in sequence, score >= 90 is evaluated first. If you placed score >= 60 first, every score above 60 would return "D", and the later branches would never run. The elif structure ensures only one branch executes, which is more efficient and clearer than a series of independent if statements.

Common Mistakes with Elif Chains

One frequent error is using multiple if statements instead of elif when the branches are mutually exclusive. Consider:

python
if score >= 90: result = "A" if score >= 80: result = "B"

If score is 95, both conditions are true, and result ends up as "B". Using elif prevents this because the second condition is only evaluated if the first is false.

Another mistake is placing else before an elif, which is invalid syntax. The else must always be last. Also, forgetting the else can leave a variable unbound if no condition matches, leading to a NameError later. Ordering conditions from most specific to least specific is a good habit.

When to Use a Dictionary Instead of if/elif/else

For simple equality checks, a dictionary lookup is often more concise and faster. For example, mapping status strings to HTTP codes:

python
status_codes = { "ok": 200, "not_found": 404, "server_error": 500, } code = status_codes.get(status, 400)

Dictionary lookup is O(1) on average; an if/elif chain evaluates conditions one by one, so in the worst case it checks every condition. However, a dictionary only works for exact matches on hashable keys. If you need range comparisons, like score >= 90, or conditions that combine multiple variables, if/elif/else is the appropriate tool. The choice depends on the nature of the conditions and the expected number of branches.

Performance and Maintainability Considerations

For a small number of conditions, the performance difference between an if/elif chain and a dictionary is negligible. The dominant cost is usually evaluating each condition. If a condition involves an expensive function call, ordering the chain to check cheap conditions first can reduce work. Long chains can also become hard to read and maintain. When you find yourself repeating similar patterns, consider refactoring into a data structure or lookup table. For instance, a list of tuples with a predicate and a result can replace a long chain:

python
def classify(value): rules = [ (lambda x: x > 100, "high"), (lambda x: x > 50, "medium"), (lambda x: x > 0, "low"), ] for predicate, result in rules: if predicate(value): return result return "none"

This approach centralizes the logic and makes it easier to add or remove rules, though it may be less readable for simple cases.

Handling Complex Conditions and Nested Logic

Sometimes you need to combine multiple variables. You can nest if statements inside branches, but that can increase indentation depth and reduce readability. Flattening with logical operators often improves clarity:

python
if user.is_active and user.role == "admin": # admin actions elif user.is_active and user.role == "editor": # editor actions else: # inactive or unknown role

This avoids deep nesting and makes the conditions explicit. However, if the logic is genuinely hierarchical, nested if blocks may be more natural. Use the structure that matches the decision tree you are implementing.

Edge Cases: Truthiness and Falsy Values

Python evaluates conditions using truthiness, not just True and False. An empty list, empty string, or None is falsy. This can lead to subtle bugs:

python
items = [] if items: process(items) else: handle_empty()

The if items branch is skipped because an empty list is falsy. Similarly, if not items is true for empty collections. The elif conditions are only evaluated if all previous conditions are false. You can rely on that ordering when later checks depend on earlier branches not matching.

Compatibility Notes

The if/elif/else syntax is stable across Python 3.x and requires no special imports or flags. It is a core language feature and has not changed since its introduction.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.