Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

If, elif and else statements in Python

After this lesson: I can make a program choose with if, elif and else.

55 min lesson4 commandsEveryday Linux commands lab: the thirty commands engineers type from memory

Why a child pays less than an adult

An if statement makes a Python program choose what to do by testing a condition. Without choices a program does the same thing every time. With them it can charge a child one price and an adult another.

A cinema has several prices. The till has to look at the age and pick the right one.

By the end of this lesson

Note

I can make a program choose with if, elif and else.

Key words

WordWhat it meansExample
Conditiona test that is either True or Falseage < 16
Comparisona test that sets two values side by sideage == 18
Branchone path the program may take
Indentationthe spaces at the start of a line that show which block it belongs to
Boolean operatorand, or or not, which join conditions together
Nestedplaced inside another if

The cells students fill in are left blank in this preview.

An if statement tests a condition

Write if, then a condition, then a colon. The lines under it, pushed in by four spaces, run only when the condition is True. This pushing in is indentation, and Python uses it to know which lines belong together.

Add else: and the lines under it run when the condition is False. Exactly one of the two branches runs.

Worked example: six comparisons with age 16

ComparisonMeansWith age = 16
age == 16is equal toTrue
age != 16is not equal toFalse
age < 16is less thanFalse
age <= 16is less than or equal toTrue
age > 16is greater thanFalse
age >= 16is greater than or equal toTrue

The cells students fill in are left blank in this preview.

Three comparisons of 15 and 16

Command
python3 -c "print(15 < 16, 15 == 16, 15 != 16)"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A fare chosen by age

Code: python
age = 12
if age < 16:
    print("Child fare")
else:
    print("Adult fare")
# Change age to 30 and run again.

Save the program as a file

Command
printf 'age = 12\nif age < 16:\n    print("Child fare")\nelse:\n    print("Adult fare")\n' > fare.py

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Run the file

Command
python3 fare.py

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A common mistake

Warning

Many people write if age = 16: to ask a question. A single = stores a value, and Python stops with a syntax error. Use == when you are asking whether two values are equal.

elif adds more branches to the same choice

A choice often has more than two outcomes. Put elif (short for else if) between the if and the else.

Python tests from the top and runs the first branch whose condition is True. It then skips the rest. So put the narrowest test first.

Four prices in one ladder

Code: python
age = 70
if age < 5:
    price = 0
elif age < 16:
    price = 4
elif age >= 65:
    price = 5
else:
    price = 8
print("Price:", price)
# Try ages 3, 10, 30 and 65.

and, or and not join conditions

and is True only when both sides are True. or is True when at least one side is True. not turns True into False and back.

A cinema might say: weekend prices apply when the day is Saturday or Sunday.

Worked example: and, or and not

ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

The cells students fill in are left blank in this preview.

Join two conditions

Code: python
age = 20
day = "Sat"
is_adult = age >= 16
is_weekend = day == "Sat" or day == "Sun"
print(is_adult, is_weekend)
print(is_adult and is_weekend)
print(not is_weekend)
# Change day to "Tue" and run again.

Is 20 an adult weekday age?

Command
python3 -c "print(20 >= 16 and 20 < 65)"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A nested if sits inside another if

Sometimes the second choice only matters after the first. Put an if inside a branch of another if, and indent it four more spaces.

You can often write the same thing with and. Use whichever is easier to read.

Age first, then the day

Code: python
age = 30
day = "Sat"
if age >= 16:
    if day == "Sat" or day == "Sun":
        print("Adult, weekend: 10")
    else:
        print("Adult, weekday: 8")
else:
    print("Child fare")
# Change day to "Tue" and run again.

Going further

Change fare.py so that it asks about a student. Add a second variable, has_card, set to True or False. A student with a card gets 1 off the adult fare.

Write the plan in pseudocode first. Then decide whether a nested if or an and reads better.

About this lab and its source: Everyday Linux commands lab: the thirty commands engineers type from memory

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.