elif in Python: chaining several conditions

elif adds a test that is only evaluated once the previous ones have failed. Exactly one branch runs, the first whose condition is true.
6 min read
Believemy logo

Definition

A program rarely has only two outcomes. A signup form does not answer "valid" or "invalid": it tells apart an empty field, a password that is too short, an address already in use. Yet an if followed by an else opens only two doors. As soon as a third one is needed, a word is missing to say "otherwise, let us try this instead".

That word is elif, short for "else if". It adds a test to a conditional chain, and that test is evaluated only when every test before it has failed. An if can therefore be followed by as many elif branches as needed, then closed by an optional else that catches whatever no branch caught.

Here is a complete chain, turning a temperature into clothing advice. What matters is not the logic, which is three thresholds, but the order those thresholds are written in.

PYTHON
temperature = 12

# Python walks down the tests one by one and stops at the first true one
if temperature > 30:
    advice = "Stay in the shade"
elif temperature > 20:
    advice = "Light layer is enough"
elif temperature > 10:
    advice = "Take a jacket"
else:
    advice = "Coat required"

Follow Python through this example. It tries temperature > 30, false at 12 degrees. It moves to the second test, false as well. The third one, temperature > 10, is true: it runs the line below it, then leaves the chain. The else is never even looked at.

So exactly one branch runs, always the first whose condition is true. The later ones are not merely skipped, they are never evaluated. That distinction matters as soon as testing costs something: a test that queries a database or calls a remote service, placed at the end of the chain, only ever runs in the rare cases where everything else has failed.


Why elif beats a nested if

elif adds no new capability to the language. Everything it expresses, an else holding another if would express too, with the same result. Its value lies elsewhere: in the shape the code takes once written.

Without elif, every extra alternative pushes the next block one step to the right. With four cases the last branch sits sixteen spaces from the margin, and indentation ends up taking more room than the logic it carries.

Here is the same decision written without elif, cut down to three cases to stay readable.

PYTHON
# What elif avoids: one more level for every alternative
if temperature > 30:
    advice = "Stay in the shade"
else:
    if temperature > 20:
        advice = "Light layer is enough"
    else:
        if temperature > 10:
            advice = "Take a jacket"

Both versions produce exactly the same result. The first reads as a list of cases the eye scans from top to bottom; the second as a staircase, where each step forces you to remember what was already ruled out above. The gain is not measured in run time, identical either way, but in how long it will take you to read this code again in six months. This is precisely the kind of trade-off Python settles in favour of readability.

Good to know

The word is written as a single piece. else if in two words, a natural reflex for anyone coming from JavaScript or C, does not work: after else, Python expects a colon and an indented block, and reports a SyntaxError.


A chain of elif is not a run of ifs

The most common confusion is not about the syntax, but about what happens when it is forgotten. Three if statements written one under the other look a lot like a chain of elif: same alignment, same tests, same look on screen. The behaviour has nothing in common.

Take the temperature example again and replace the two elif branches with if. Python no longer sees a chain, but three independent questions asked one after another. At 35 degrees the first is true, the second is true as well, the third too: advice receives three values in a row and keeps the last one, "Take a jacket". The else, now attached to the final if alone, stops being the safety net of the whole thing.

Nothing crashes, and that is the problem: the program suggests a jacket on a heatwave day. The distinction fits in one sentence. Successive if statements ask independent questions, several of which can be true at once; a chain of elif asks a single multiple-choice question.

Warning

This mistake only shows up on values that satisfy more than one test at a time. At the 12 degrees of the example, the faulty version and the correct one give the same advice: the defect passes the tests and surfaces in production, on the first extreme value it meets.


Order is a trap

On numeric thresholds, a badly ordered chain gives a wrong answer without raising anything at all. Put the > 10 test first: a temperature of 35 degrees matches it, that branch runs, and the two stricter tests below are never reached. The program runs fine, it simply gives the wrong advice.

The cause lies in how Python reads the chain. It does not look for the test best suited to the value, it takes the first one that answers true. Nobody will do the sorting for you: order the tests from most restrictive to broadest, from the rarest case towards the most common one.

That leaves the situation where branches cannot be ordered. A switch on country names, statuses or commands has neither a rare case nor a broad one, and the question of ordering no longer makes sense. A dictionary is almost always clearer there than a chain of ten elif branches: each key maps straight to a value or to a function to call, and adding a case becomes a line of data rather than one more branch of code.


Frequently asked questions

Question

How many elif branches can be chained?

The language sets no limit. Readability, however, gives way around five or six branches: past that, a mapping dictionary or the match statement reads far better. A long chain often signals data that deserves to be structured rather than unrolled into code.

Question

Can an elif exist without an if?

No. A stray elif raises a SyntaxError before the program even starts, since it only makes sense attached to the if that opens the chain. The same rule applies to else, which must always close an existing structure.

Question

Should a chain always end with else?

It is not required, but it is wise as soon as a value must exist in every case. Without a final branch, a variable assigned in some branches only does not exist at all elsewhere, and reading it raises a NameError much further down the program, at a spot that says nothing about the real cause. Structuring decisions like this one is worked through on real cases in our Python course.

Related terms

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.