CodeRigor

LESSON

Make decisions with if, elif and else

Compare values, read true/false conditions, choose between blocks of code with if, elif and else, and combine conditions with and, or and not.

Every program so far ran the same statements in the same order every time. Real programs choose: a ticket machine charges a child less than an adult, a game says "too high" or "too low". This lesson shows how a program decides which statements to run.

Conditions are true or false

A condition is a question that Python can answer with yes or no. Python's words for yes and no are True and False. These two values have their own type, called Boolean (or bool).

You build conditions with comparison operators:

Operator Meaning
== is equal to
!= is not equal to
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
Python
age = 16
print(age < 18)
print(age == 16)
print(age != 16)
print(age >= 16)

This prints True, True, False and True.

Take care with the two equals signs. One = assigns: age = 16 makes the name refer to 16. Two, ==, compares: age == 16 asks whether the value is 16.

Strings can be compared with == as well. Capital letters count: "yes" == "Yes" is False.

if runs a block only when its condition is true

Python
temperature = 31
if temperature > 30:
    print("It is hot.")
    print("Drink some water.")
print("Done.")

This prints all three lines. Change 31 to 20 and run it again: only Done. is printed.

An if statement has two parts:

  • A first line with the word if, a condition and a colon :.
  • A block: the lines underneath that are pushed in from the left edge. Pushing lines in is called indenting them. Use four spaces.

The block runs only when the condition is true. The indentation is how Python knows which lines belong to the if. print("Done.") is back at the left edge, so it is not part of the block and always runs.

else gives the other path

Add else: and a second block for what to do when the condition is false. Exactly one of the two blocks runs.

Python
age = 15
if age >= 18:
    print("You may vote.")
else:
    print("You are too young to vote.")

This prints You are too young to vote..

elif chooses between several paths

elif is short for "else if". It adds another condition, which is checked only when the ones above it were false. You can have as many elif parts as you need, and an optional else at the end for "none of the above".

Python
age = 9
if age < 5:
    print("Free")
elif age < 16:
    print("Child ticket")
else:
    print("Adult ticket")
print("Enjoy your visit.")

This prints Child ticket and then Enjoy your visit.. Step through the diagram to see which lines run and which are skipped.

Following one value through if, elif and else
start / 5 ⇄ code
With age = 9 the first condition is false, the second is true, and its block runs. Python then skips the rest of the chain and carries on below it.
Following one value through if, elif and else
With age = 9 the first condition is false, the second is true, and its block runs. Python then skips the rest of the chain and carries on below it.

Python checks the conditions from the top and runs the block of the first one that is true. At most one block in a chain runs, so the order of the conditions matters. A nine-year-old is also "less than 100", but that would never be reached if it were written below age < 16.

A chain picks exactly one path
start / 4
Each condition is asked only if every condition above it was false. else catches everything that is left.
A chain picks exactly one path
Each condition is asked only if every condition above it was false. else catches everything that is left.

Combining conditions

Three words join conditions together:

  • and is true when both sides are true.
  • or is true when at least one side is true.
  • not turns true into false and false into true.
Python
age = 10
height = 130
print(age >= 8 and height >= 120)
print(age >= 12 or height >= 120)
print(not age >= 8)

This prints True, True and False. The first line needs both tests to pass, and they do. The second needs only one, and the height test passes. In the third, age >= 8 is true, so not makes it false.

A combined condition goes after if like any other:

Python
day = "Sat"
if day == "Sat" or day == "Sun":
    print("Weekend")
else:
    print("Weekday")

This prints Weekend. Each side of or must be a complete condition. day == "Sat" or "Sun" does not mean what it says in English.

Three errors you will meet

A missing colon.

Python
age = 9
if age < 16
    print("Child ticket")
Text
  File "main.py", line 2
    if age < 16
               ^
SyntaxError: expected ':'

The ^ points at the end of line 2, and the message says what belongs there. Every if, elif and else line ends with a colon.

A block that is not indented.

Python
age = 9
if age < 16:
print("Child ticket")
Text
  File "main.py", line 3
    print("Child ticket")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

Python reports line 3 because that is where it expected to find indented lines. The message also names line 2, where the if is. Indent line 3 by four spaces.

One equals sign where two are needed.

Python
age = 16
if age = 16:
    print("Sixteen")
Text
  File "main.py", line 2
    if age = 16:
       ^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

"Invalid syntax" means Python could not make sense of the text at the marked place. The hint is right: a comparison needs ==. (Ignore :=; it is a feature this unit does not use.)

One mistake produces no message at all: indenting a line that should not be in the block, or forgetting to indent one that should. The program runs but does the wrong thing. When output is missing or appears when it should not, check the indentation first.

What you can do now

You can write conditions, choose between two or more paths, and combine tests with and, or and not. In the exercises you will predict which branch runs, then write a program that makes a three-way decision from two answers.

Next: repeat steps with loops, so that a program can do something many times without you writing it many times.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

The whole lecture is this lesson: comparisons, if, elif, else, or and and, with every program built and corrected live. The first 29 minutes (to 'Chaining Comparison Operators') cover everything used here.