Learn When to Use elif in Python: Absolute Beginners Tutorial

The elif keyword is what Python uses to test a second (or third, or fourth) condition when the first one is False. Understanding exactly when to reach for elif instead of a second if is one of those early decisions that shapes how clearly your code communicates.

Every program eventually needs to make decisions. Python's if statement handles a single decision: do this or skip it. But real problems have more than two outcomes. A traffic light is not just red or not-red. A grade is not just passing or failing. elif is the mechanism Python provides for mapping those additional outcomes without re-evaluating everything from scratch.

What elif Does and Why It Exists

elif is a contraction of "else if." It attaches to an existing if block and supplies a new condition to test — but only when the preceding condition was False. The moment any condition in the chain evaluates to True, Python executes that block and skips every remaining elif and else.

The simplest form looks like this:

python
temperature = 85

if temperature >= 100:
    print("boiling")
elif temperature >= 70:
    print("warm")
else:
    print("cool")

With temperature = 85, the first condition (temperature >= 100) is False. Python moves to the elif, finds 85 >= 70 is True, prints "warm", and stops. The else block never runs.

Note

elif must follow an if (or another elif). It cannot appear as the first clause in a conditional block. Attempting to write elif without a preceding if raises a SyntaxError.

The three building blocks of a full conditional chain are worth naming clearly:

  • if — opens the chain; always required; tested first.
  • elif — optional; tested only when all preceding conditions were False; you can have as many as needed.
  • else — optional; has no condition; runs only when every preceding condition was False.

A practical example that matches this pattern is mapping a numeric score to a letter grade. There are five distinct outcomes, none of which should overlap:

python
score = 78

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(grade)  # C

Because the conditions descend in value, each range is implicitly bounded. When Python reaches score >= 70, it already knows the score is below 80 (otherwise the previous elif would have matched). This is one of the cleaner patterns in Python — each branch handles exactly one slice of the number line.

Pro Tip

Order conditions from most restrictive to least restrictive. Because Python stops at the first match, a broad condition placed early can absorb values that should have matched a more specific condition placed later.

code builder click a token to place it

Build a correct Python if/elif/else chain that prints "freezing" when temp is below 32, "cold" when below 60, and "warm" otherwise:

your code will appear here...
elif else: if print("cold") temp < 60: print("warm") temp < 32: print("freezing") temp > 32:
Why: The chain must start with if, followed by the most restrictive condition (temp < 32). The second condition uses elif — not a second if — to ensure it only runs when the first was False. The final else catches everything remaining. temp > 32: is a distractor that would miss the value 32 itself.

elif vs. a Second if Statement

New Python writers sometimes wonder why elif exists at all. After all, you could write a second if statement and get a result. The difference is subtle but important: when you write a chain of independent if statements, Python evaluates every one of them. When you use elif, Python stops as soon as a match is found.

Consider this side-by-side comparison using a variable role:

python
# --- Using separate if statements ---
role = "admin"

if role == "admin":
    print("full access")    # prints
if role == "editor":
    print("edit access")    # does not print
if role == "viewer":
    print("read-only")      # does not print

# All three conditions are evaluated regardless.


# --- Using elif ---
if role == "admin":
    print("full access")    # prints, chain stops here
elif role == "editor":
    print("edit access")    # skipped
elif role == "viewer":
    print("read-only")      # skipped

For string comparisons the difference is mainly one of efficiency and intent. But with numeric comparisons the difference matters in a more concrete way:

python
score = 95

# --- Separate if statements: two blocks fire ---
if score >= 90:
    print("You earned an A")    # prints
if score >= 80:
    print("You earned a B")     # also prints — unintended!

# --- elif: only one block fires ---
if score >= 90:
    print("You earned an A")    # prints
elif score >= 80:
    print("You earned a B")     # skipped correctly

With a score of 95 and two separate if statements, both conditions are True, so both blocks print. That is logically wrong for a grading system — a score of 95 should map to exactly one letter grade. elif enforces that mutual exclusivity.

Common Mistake

Using a second if instead of elif when conditions overlap is one of the most frequent logic errors in early Python code. If your conditions are mutually exclusive — meaning only one should ever be true at a time — always use elif.

Evaluation behavior
Tested only if all preceding conditions were False. Stops the chain on first True match.
Use when
Conditions are mutually exclusive and only one branch should ever run per execution.
Evaluation behavior
Every if is evaluated independently, every time. Multiple blocks can run in a single pass.
Use when
Conditions are independent and multiple blocks may legitimately run, such as validating several separate fields.
Evaluation behavior
No condition to test. Runs its block when the preceding if condition was False.
Use when
There are only two possible outcomes (True or everything else). No additional conditions need to be tested.
spot the bug click the line that contains the bug

The function below is supposed to return a shipping tier based on order total. One line prevents it from working correctly. Click the line you think is wrong, then hit check.

1 def shipping_tier(total):
2 if total >= 100:
3 return "free shipping"
4 if total >= 50:
5 return "standard shipping"
6 else:
7 return "express only"
The fix: Line 4 should read elif total >= 50: instead of if total >= 50:. Because line 4 starts a new if, it is evaluated independently. An order totaling $120 passes the first if (returns "free shipping") but the second if is also True — and its attached else will fire if total < 50 on any run, creating inconsistent behavior. Using elif ties the second check to the first, ensuring only one return path runs.

Chaining Multiple elif Clauses

Python allows as many elif clauses as a problem requires. There is no syntactic limit. In practice, the need for more than four or five branches often signals that a dictionary lookup or Python's match statement (introduced in Python 3.10) would express the logic more cleanly — but for straightforward range-based decisions, a well-ordered chain of elif clauses is idiomatic and clear.

Here is a real-world example: a function that returns a time-of-day label based on the hour in 24-hour format.

python
def time_of_day(hour):
    """Return a label for the given 24-hour clock value."""
    if hour < 0 or hour > 23:
        return "invalid hour"
    elif hour < 6:
        return "night"
    elif hour < 12:
        return "morning"
    elif hour < 17:
        return "afternoon"
    elif hour < 21:
        return "evening"
    else:
        return "night"

print(time_of_day(3))   # night
print(time_of_day(9))   # morning
print(time_of_day(14))  # afternoon
print(time_of_day(19))  # evening
print(time_of_day(23))  # night

A few things worth noting in that function. The first condition validates the input and returns early if the value is out of range — a common pattern that keeps the rest of the chain clean. Each subsequent elif only runs if all previous conditions were False, so the boundaries are implicitly enforced. The final else catches hours 21 through 23 without requiring an explicit comparison.

What happens when no condition matches

If no condition in an if/elif chain matches and there is no else, Python does nothing. Execution continues on the line after the entire block without error. This is valid and sometimes exactly what you want:

python
status_code = 200

if status_code == 404:
    print("not found")
elif status_code == 500:
    print("server error")
# No else — 200 produces no output and that is intentional.
# Code continues here regardless.
Note

If you need to guarantee that at least one branch always runs, add an else clause. Omitting else means "silently do nothing when nothing matches" — which is fine for optional actions but problematic when your code depends on a variable being set inside the conditional block.

elif with compound conditions

The condition after elif can be any valid Python boolean expression — comparisons, function calls, membership tests, and compound conditions using and, or, and not.

python
age = 17
has_id = False

if age >= 21:
    print("admitted")
elif age >= 18 and has_id:
    print("admitted with ID")
elif age >= 16:
    print("minor — restricted access")
else:
    print("not admitted")

Here, the second elif uses a compound condition. Both age >= 18 and has_id must be True for that branch to fire. With age = 17 and has_id = False, neither the first condition nor the second matches, so Python falls through to the third elif and prints "minor — restricted access".

"Flat is better than nested." — The Zen of Python (PEP 20)

Long elif chains stay flat — one level of indentation — which is preferable to deeply nested if statements. If you find yourself nesting if inside if inside if, consider whether elif at the outer level would express the same logic without the extra indentation.

How to Use elif in Python

Writing a correct elif chain takes four deliberate steps. Each one avoids a specific category of mistake.

  1. Start with an if statement

    Write if followed by your first condition and a colon. Indent the code block that should run when that condition is True. This is the required opening of every conditional chain — elif cannot appear without it.

  2. Add an elif clause at the same indentation level

    On the next line at the same indentation as if, write elif followed by a new condition and a colon. Indent its code block by the same amount as the if block. The elif keyword signals Python that this check should only happen when the preceding condition was False.

  3. Order conditions from most specific to least specific

    Python stops at the first True condition. Place the most restrictive tests first. For numeric ranges, descend from the highest threshold downward. For string checks, test specific values before testing broader categories. A broad condition placed first will shadow any more specific conditions below it.

  4. Optionally add an else clause as a fallback

    After all elif clauses, you may add a final else with no condition. Its block runs when none of the preceding conditions matched. else is optional — omit it if no fallback behavior is needed. Include it when your code must handle every possible input, especially to set a default value or raise an informative error.

Python Learning Summary Points

  1. elif is only evaluated when all preceding if and elif conditions in the same chain were False. The moment a match is found, all remaining branches are skipped.
  2. When conditions are mutually exclusive — meaning only one should be True at a time — always use elif rather than a second independent if. A second if can fire even when the first one already did.
  3. Order your conditions from most restrictive to least restrictive. For descending numeric thresholds, each boundary is implicitly enforced because Python has already ruled out higher values by the time it reaches a lower elif.
  4. The else clause is optional. Without it, if no condition matches, Python silently moves past the entire block. Add else when your program requires a guaranteed fallback or must set a value in every case.
  5. Long elif chains (more than five or six branches) may be a sign to consider a dictionary mapping or, for Python 3.10+, a match statement — both of which can express the same logic with less repetition.

The rule of thumb is straightforward: use elif whenever a new condition should only be checked after a previous condition has failed, and whenever you want to guarantee that at most one branch runs. Everything else — independent checks, multiple simultaneous conditions — belongs in separate if statements.

check your understanding question 1 of 5

Frequently Asked Questions

elif stands for "else if." It is used between an if statement and an optional else to test an additional condition when the preceding if (or elif) condition was False.

Use elif when the conditions are mutually exclusive and only one branch should ever run. A second if statement always evaluates independently, so both blocks could execute if both conditions are True. elif guarantees that once a matching branch runs, all remaining branches are skipped.

Python places no hard limit on the number of elif clauses in a single if statement. You can chain as many as the logic requires. In practice, long elif chains often signal that a dictionary or match statement might express the logic more clearly.

No. The else clause is optional. An if block can consist of just if and one or more elif clauses with no else. Without else, if no condition matches, Python simply moves on without executing any branch.

No. elif cannot appear without a preceding if statement. Attempting to use elif as the opening clause of a block produces a SyntaxError.

elif tests a specific condition and only runs its block if that condition is True and all previous conditions were False. else has no condition — its block runs when none of the preceding if or elif conditions were True. else is a catch-all; elif is a targeted check.

Python evaluates conditions from top to bottom and executes only the first matching branch. If the first elif condition is True, its block runs and all remaining elif and else clauses are skipped, even if they would also evaluate to True.

Yes. With elif, Python stops evaluating once a matching branch is found. With separate if statements, every condition is tested regardless of previous results. For mutually exclusive conditions, using elif is more efficient and communicates intent more clearly.

Yes. The condition after elif can be any valid Python boolean expression, including compound conditions using and, or, and not, as well as comparisons, membership tests with in, and function calls that return a boolean.

The syntax is elif condition: followed by an indented block. The colon is required and the block must be indented consistently with the surrounding if blocks. elif must follow an if or another elif; it cannot appear first in a chain.

Key Concepts
  • elif
  • if statement
  • else clause
  • mutual exclusivity
  • short-circuit evaluation
  • boolean expression
  • match statement
  • indentation