Handling Cases with Elif

Introduction: When Two Paths Are Not Enough

Welcome back to Making Decisions in Python! We can already guard a block behind a condition and offer an alternative with else. That gives us exactly two routes, no more.

Now consider a familiar task: turning a numeric score into a letter grade. A score of 95 earns an A, 85 earns a B, 75 earns a C, and anything lower earns an F. That is four outcomes, and an if/else pair simply cannot express four possibilities on its own.

The keyword that solves this is elif, short for "else if." It lets us insert as many middle paths as we need between the first if and the final else. In this lesson, we will build such a chain, learn why only the first matching branch runs, and see what happens when the else is missing.

The Shape of an if/elif/else Chain

Before writing real values, let's look at the general template so the structure is clear:

if first_condition:
    # runs when first_condition is True
elif second_condition:
    # runs when first_condition is False and second_condition is True
elif third_condition:
    # runs when the two conditions above are False and this one is True
else:
    # runs when every condition above is False

A few syntax details deserve attention:

  • Every elif aligns with if at the same indentation level; they are partners in one chain, not nested statements.
  • Unlike else, each elif carries its own condition, followed by its own colon and its own indented block.
  • We may write any number of elif branches, and the optional else must always come last.

The promise of the whole structure is simple: at most one block in the chain runs.

Building the Grading Chain Step by Step

Let's grow the grading program one branch at a time, starting with a single test:

score = 75

if score >= 90:
    print("Grade: A")

Right now, only scores of 90 and above produce anything; our 75 is silently ignored. Adding branches gives every score a home:

score = 75

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

Each addition widens the coverage: the first elif handles the 80 range, the second handles the 70 range, and the closing else catches everything below 70. With the else in place, no score is left without an answer.

Tracing the Chain: Why score = 75 Prints "Grade: C"

Let's follow Python through the finished program with score set to 75. It tests 75 >= 90, which is False, so it skips that block and moves to the next test. It tests 75 >= 80, also False, so it moves down again. It tests 75 >= 70, which is True, so that block finally runs:

Grade: C

Two observations matter here. First, Python never reaches the else: once a condition is True, the rest of the chain is skipped entirely, including any tests that come after it. Second, only one line was printed, even though several conditions could have described our score. This behavior has a name: first-match behavior.

First Match Wins: Why the Order of Branches Matters

Because the first match wins, the order of our branches decides the result. Watch what happens if we put the loosest test at the top:

score = 95

if score >= 70:          # Careless order!
    print("Grade: C")
elif score >= 80:
    print("Grade: B")
elif score >= 90:
    print("Grade: A")

A score of 95 satisfies 95 >= 70 immediately, so Python prints Grade: C and never looks at the stricter tests below. The rule to remember: when numeric ranges overlap, order the conditions from most restrictive to least restrictive.

There is a pleasant flip side to this. Since a branch is only reached when every earlier condition was False, we can write a plain score >= 80 instead of a compound score >= 80 and score < 90; the earlier test already ruled out the higher scores.

Switching Branches by Changing the Input

As before, the quickest way to confirm that a branch works is to feed the program different data. Let's change only the first line of our correct chain:

score = 95        # the first condition is now True

Python finds a match on the very first test and stops there:

Grade: A

Now let's try a failing score instead:

score = 40        # every condition is False

All three tests fail, so the fallback runs:

Grade: F

Notice the consistency: whatever value we choose, exactly one message appears. Flipping the input and checking which single line shows up is the fastest way to verify each branch of a chain.

Chains Without an else: When Nothing Runs

The else is optional, so let's see what a chain looks like without it. Here is the same program with the fallback removed, still using our failing score:

score = 40

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")

Python tests 40 >= 90, then 40 >= 80, then 40 >= 70, and all three are False. With no branch left to fall back on, the chain ends quietly:

(nothing is printed)

This is not an error, just three false conditions in a row. The contrast is worth memorizing: with an else, exactly one block always runs; without one, either one block runs or none do. Skipping the else is a fine choice when we only want to act on specific cases, but it can also hide a bug, since an unexpected value produces no result and no complaint.

Picturing the Chain as a Flowchart

Sketching the chain shows why it is often called a ladder. Each diamond is a test, and every "No" answer drops us onto the next rung:

Flowchart of an if/elif/else grading chain showing first-match behavior

Every shape maps onto one line of code: the diamonds are the if and elif headers, each grade box is the indented print() inside that branch, and the bottom box is the else block. All routes merge at the same point, which is where any unindented code after the chain would run. If we drop the else, that last "No" arrow simply goes straight to the merge point without printing anything.

Conclusion and Next Steps

Let's gather the takeaways. elif adds extra conditional paths, each with its own condition and colon, all aligned with the opening if. Python evaluates the conditions from top to bottom and runs only the first one that is True, skipping everything else in the chain. Because of that, branch order controls the outcome whenever ranges overlap, and later conditions can stay simple. Finally, an else guarantees a fallback; without one, a value that matches nothing produces no output at all.

Next, we will use Boolean variables directly as conditions and untangle the pitfalls of stacked and accidentally nested branches.

Time to grade some papers: in the practices ahead, you will build a grading chain, send the program down a different branch by changing the score, strip out the else and listen to the silence, and then restore it so every value gets an answer again.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal