Python If Else Statement: Use Elif Clearly

Different values can call for different actions in a script. A Python branch chain tests conditions in order and runs the first matching block.

I’ll show how to build an if/elif/else chain and why the order of its conditions matters.

TL;DR

A Python if/elif/else chain checks conditions in order and runs the first matching block.

  • Use if for the first condition and optional elif clauses for alternatives.
  • Use else as an optional fallback when none match.
  • Indent each branch body and align elif and else with if.

What Is an If-Else Statement in Python?

An if statement chooses whether Python runs an indented block. Its condition is an expression Python tests as true or false, often a comparison such as score >= 60.

Python calls the block of statements under a clause its suite. A colon ends the clause header, and indentation marks which statements belong to that branch. A comparison produces a Boolean value, True or False, while other values can also be tested for truth.

score = 72

if score >= 60:
    print("Pass")

Because the condition is a comparison and the input values are numeric, I use explicit thresholds here. A comparison makes the intended boundary visible to the next person reading the branch.

How to Write a Python If-Else Statement Step by Step

Build the chain from the first test to the fallback. I ran the example in the named file branch_demo.py with the command python3 branch_demo.py. It classifies four scores, including one below the valid range.

Step 1: Write the first if condition

Start with the condition that should be checked first, then put its action in an indented suite. This example treats a negative score as invalid before checking performance bands.

if score < 0:
    return "invalid"

Keep the colon and indented body together. The same indentation level marks the end of the suite.

Step 2: Add elif clauses for alternatives

Use elif, short for “else if,” when another test should run only after earlier tests fail. Each clause belongs at the same indentation as its matching if.

elif score < 60:
    return "needs work"
elif score < 80:
    return "passing"

The tests use increasing thresholds, so a score of 72 reaches the second elif and returns “passing.” Python skips later clauses after that return.

Step 3: Add an optional else fallback

Add else when every value that reaches the end should receive a default result. It has no condition and must follow all elif clauses.

else:
    return "strong"

The full function used for that output is shown here.

def classify(score):
    if score < 0:
        return "invalid"
    elif score < 60:
        return "needs work"
    elif score < 80:
        return "passing"
    else:
        return "strong"


for score in (-3, 42, 72, 95):
    print(f"{score}: {classify(score)}")

The captured output is:

-3: invalid
42: needs work
72: passing
95: strong
Terminal output from the Python if-else classification example

The negative input reaches the first branch, 42 reaches the first elif, and 95 reaches else. The order matters: once one branch runs, later conditions in this chain are skipped.

What Should You Check in an If-Else Chain?

Choose a chain when only one outcome should run, and use separate if statements when several actions may apply. These checks prevent branch-order and indentation mistakes.

Does an if statement need an else?

No. An if can stand alone, and else is optional. If no condition matches and there is no else, Python continues after the whole statement without running a branch.

if score >= 60:
    print("Pass")

print("Finished")

Use separate if statements for independent facts, such as checking whether a number is positive and whether it is even. An elif chain would skip the second test after the first match.

Why does condition order matter?

Python stops at the first true branch, so order overlapping tests from specific to broad. A broad condition placed first can make later, narrower conditions unreachable. For example, the second branch below is unreachable because every score below zero also satisfies score < 100.

if score < 100:
    result = "under 100"
elif score < 0:
    result = "negative"

The second branch is unreachable because any score below zero already satisfies score < 100. Reverse the tests so the negative case comes first.

What counts as a true condition?

Empty strings and empty collections are false, while non-empty ones are true. When zero or an empty value has a distinct meaning, compare the value explicitly. For combined tests, and requires both sides to be true, while or requires either side.

Condition valueTruth resultUse it when
empty string or empty listFalseNo value or items should take the branch
non-empty string or listTruePresence of content is the test
zeroFalseZero should count as no amount

A nested if can express a second decision inside a branch, but a long staircase of nesting is harder to scan than an elif chain. For a required but unfinished suite, use pass temporarily. Python rejects an empty suite.

See Python indentation and the pass statement for those related rules.

A return statement exits its function as soon as that branch runs. Without return, Python finishes the chosen suite and continues with the first statement after the entire if/elif/else structure. Use break only when the conditional is inside a loop and you intend to leave that loop.

For a simple two-way value, a conditional expression fits on one line: status = “adult” if age >= 18 else “minor”. Keep the multiline form when the condition or either result needs explanation.

Conclusion: Keep Branches Clear

An if/elif/else chain checks conditions from top to bottom and runs one matching suite. Put exceptions before broad tests, align each clause with its if, and add else only when a fallback belongs in the logic.

For the language rules, see Python’s if statement tutorial and its truth-value testing reference.

FAQ

These answers cover common syntax choices that do not need a separate section.

How does a Python if-else statement end?

The indented suite ends when the next line returns to the clause’s indentation level. The full if statement ends when its body and any elif or else clauses end.

How can I reduce a long if-else statement?

Use elif for mutually exclusive tests, combine related Boolean conditions when that improves clarity, or use a conditional expression for a short two-way value. Keep separate if statements when multiple actions can apply.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 259