Skip to content
Theory · Conditions · lesson 1 of 8

if, elif and else

What you'll learn

What you'll learn:

  • choose one of several branches with if, elif and else;
  • put the conditions of a chain in the right order;
  • tell truthy values from falsy ones when they stand in a condition;
  • choose a value in one line with a conditional expression, abs, min and max.
A three-way fork with a thermometer on the signpost: if to a snowy hill, elif to a bench, else to a beach

Picture a fork where the road splits three ways. A signpost stands at the fork, and a thermometer hangs on its post. The arrows on the signpost sit one above another:

  • the top one, if, leads to a snowy hill: you go there when it is below zero;
  • the middle one, elif, leads to a park bench: you go there when it is below 20 degrees;
  • the bottom one, else, leads to the beach: you go there in every other case.

A traveler looks at the thermometer and reads the arrows from top to bottom. They take the first road that fits and do not read the remaining arrows.

So far our programs have run every line in a row. But a program often has to choose: show one message in a frost and another in the heat. The signpost with a thermometer looks like this in Python:

Python
temperature = 25
if temperature < 0:
    print("frost")
elif temperature < 20:
    print("cool")
else:
    print("warm")  # warm

Let's go through the example line by line:

  1. temperature = 25: the thermometer shows 25 degrees.
  2. if temperature < 0: checks the top arrow. The condition is false, and the line under it is skipped.
  3. elif temperature < 20: checks the middle arrow. 25 is not less than 20, so this line is skipped too.
  4. No condition fits, so else runs, and the program prints warm.

The if statement

A statement is a command that performs an action rather than producing a value: the assignment x = 1, return or if. The if statement runs the block under it only when the condition after if is true. The condition is usually a comparison from the previous theme.

It is written the same way as a function definition:

  • a colon follows the condition and else;
  • the lines of the block are shifted by 4 spaces;
  • the block ends at the first line that returns to the previous indentation.

Each such block is called a branch. The example has three branches, and exactly one of them ran.

Three parts of a chain

if

A chain starts with if. This part is required, and a chain has only one. If its condition is true, its branch runs, and everything below is skipped.

elif

elif is short for "else if". A chain may have any number of elif branches, or none at all. Python checks an elif condition only when every condition above it has turned out false.

else

else has no condition: this branch runs when every condition above it is false. A chain has only one, and it comes last. It may be left out, and then nothing runs when the conditions are false.

The first true branch

The main rule of a chain: Python checks the conditions from top to bottom and runs only the first branch with a true condition. It skips the other branches, even if their conditions are true too.

Press "Next step" and watch which lines the function goes through for -5 and which for 25.

LiveWhich branch runsstep 1 of 11 · frames: 1

First call: execution moves into place with t = -5, and print waits for the result.

Watch which lines the highlight stops on

With t = -5 both conditions are true, t < 0 and t < 20. But only the first branch ran, and the function returned 'hill'. Interviewers like to ask this: what does a chain print when two of its conditions are true? The answer is only the first true branch.

This is where the signpost analogy stops working. A traveler sees all the arrows at once, and their order on the post does not matter to them. For Python the order is everything.

If you swap the first two branches, the hill never comes up: any negative number reaches the bench first. That is why a narrow condition goes before a wide one.

return in a branch

In a function, a branch often ends with return. It ends the function at once, and the later branches are no longer checked:

Python
def size(n):
    if n >= 100:
        return "large"
    elif n >= 10:
        return "medium"
    else:
        return "small"


print(size(250))  # large
print(size(50))  # medium
print(size(5))  # small

Let's go through the call size(50):

  1. The condition n >= 100 is false, and the first branch is skipped.
  2. The condition n >= 10 is true, and the function returns "medium".
  3. else is never reached: return has already ended the function.

The second branch is checked only when n < 100, after the first condition has turned out false. So there is no need to add n < 100 and to its condition.

An empty branch and pass

A branch cannot be empty: after the colon the interpreter expects at least one indented line. When a branch has nothing to do yet, it holds pass, a statement that does nothing:

Python
balance = 0
if balance > 0:
    pass
else:
    print("empty")  # empty

Without pass the file does not run and reports IndentationError: expected an indented block after 'if' statement on line 2.

Common mistake

The colon after the condition is missing:

Python
temperature = 25
if temperature < 20  # ✗
    print("cool")
TEXT
SyntaxError: expected ':'

A syntax error stops the file before its first line runs, so even temperature = 25 is not executed. A colon is needed at the end of every line with if, elif and else.

Key points

  • if runs its branch when the condition is true, elif is checked when every condition above it is false, and else runs when all of them are false.
  • A chain runs only the first true branch, so a narrow condition goes before a wide one.
  • A colon is needed after every condition and after else.
  • An empty branch is an error, and pass fills a branch that has nothing to do.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way