Grade by Grade
A. Programming Concepts and Skills · Programming Basics: Data, Decisions and Loops

Selection: if, elif and else

A2.2 A4.2About 70 minutes
Learning goals
  • I can write if, if/else and if/elif/else statements with correct colons and indentation.
  • I can explain that only the first True branch of an elif chain runs, and order the conditions correctly.
  • I can draw a flowchart for a selection structure.
  • I can choose test values that check every branch and every boundary.

Words to know

selection
A control structure that chooses which statements to run based on a condition. Also called a decision or branching.
if statement
Runs a block of code only when its condition is True.
else
The block that runs when the if condition (and any elif conditions) are False.
elif
Short for "else if": another condition checked only if all earlier conditions were False.
block
A group of statements indented under a line ending in a colon. In Python, the indentation defines the block.
boundary value
A value right at the edge of a condition, such as 80 for mark >= 80. Bugs often hide at boundaries.
flowchart
A diagram of an algorithm: ovals for start and end, rectangles for steps, diamonds for decisions, arrows for flow.

Programs that choose

Until now, every line of your programs ran every time: pure sequence. Real programs make choices. If the temperature is below zero, a weather app says "wear a toque". If your password is wrong, a login screen refuses you. This is the second control structure: selection.

The if statement

  • if temp < 0:

The line starts with if, then a condition (a Boolean expression from Lesson 8), then a colon. The statements that belong to the if are indented underneath it, by 4 spaces. That indented group is a block. It runs only if the condition is True. The first line that is not indented is the next statement after the whole if, and it always runs.

temp = int(input("Temperature in °C: "))
if temp < 0:
print("Below freezing!")
print("Wear a toque.")
print("Have a good day.")

With 5 as input, only Have a good day. is printed, because the indented block is skipped. Output, line by line: Temperature in °C: -8 | Below freezing! | Wear a toque. | Have a good day. (the typed input is shown after each prompt)

Indentation is part of the code

In many languages, indentation is just good style. In Python it is required: it tells Python which lines are inside the block. Use 4 spaces per level (IDLE and Thonny insert them when you press Tab). Never mix tabs and spaces. A line indented when it should not be gives IndentationError: unexpected indent; a missing indent after a colon gives IndentationError: expected an indented block.

Two-way selection: if/else

Add else: (at the same indentation as the if) for what to do when the condition is False. Exactly one of the two blocks runs, never both, never neither.

starttemp < 0 ?Trueprint("Wear a toque")Falseprint("No toque needed")print("Have a good day")
A flowchart of an if/else. The diamond is a decision. Exactly one of the two branches runs, and then both paths join and the program continues.

Multi-way selection: if/elif/else

When there are more than two cases, use elif ("else if"). Python checks the conditions from the top down and runs the block of the first True condition. Then it skips the rest of the chain. The final else (optional) catches everything that did not match.

In Ontario, a percentage mark of 80 to 100 is Level 4, 70 to 79 is Level 3, 60 to 69 is Level 2 and 50 to 59 is Level 1. Because the chain stops at the first True condition, each elif only needs to check the lower boundary: by the time Python reaches mark >= 70, it already knows the mark is not 80 or more.

mark >= 80TrueLevel 4Falsemark >= 70TrueLevel 3Falsemark >= 60TrueLevel 2Falsemark >= 50TrueLevel 1Falsebelow Level 1continue
An if/elif/else chain checks the conditions in order and runs only the first branch whose condition is True. A mark of 85 is also ≥ 70, but it stops at Level 4.
mark = int(input("Mark (%): "))
if mark >= 80:
level = "Level 4"
elif mark >= 70:
level = "Level 3"
elif mark >= 60:
level = "Level 2"
elif mark >= 50:
level = "Level 1"
else:
level = "below Level 1"
print(f"A mark of {mark} is {level}.")

The chain from the flowchart, in code. Output, line by line: Mark (%): 74 | A mark of 74 is Level 3. (the typed input is shown after each prompt)

Worked example

Example 1: Order matters

A student wrote the level program with the conditions in the opposite order: if mark >= 50: first, then elif mark >= 60:, elif mark >= 70:, elif mark >= 80:. What does it print for a mark of 92? Why?

  1. Python checks mark >= 50 first. 92 ≥ 50 is True, so it runs that block: Level 1.
  2. Because that was the first True condition, all the elif branches are skipped, even though 92 ≥ 80 is also True.
  3. Fix: when testing with >=, check the largest threshold first. (With <, check the smallest first.) Or give every branch both boundaries, like elif 70 <= mark < 80:, which works in any order.

It prints Level 1 for 92 (and for every mark of 50 or more), which is wrong. The most restrictive condition must come first.

Worked example

Example 2: `elif` versus separate `if`s

Compare these two versions for n = 15:

Version A

  • if n % 3 == 0:
  •     print("Fizz")
  • elif n % 5 == 0:
  •     print("Buzz")

Version B

  • if n % 3 == 0:
  •     print("Fizz")
  • if n % 5 == 0:
  •     print("Buzz")
  1. 15 % 3 is 0, so both versions print Fizz first.
  2. Version A: because the first condition was True, the elif is skipped. Output: just Fizz.
  3. Version B: the second if is a separate statement, so it is always checked. 15 % 5 is also 0, so it prints Buzz too.
  4. Use elif when the cases are mutually exclusive (only one should happen). Use separate ifs when each check is independent.

Version A prints Fizz. Version B prints Fizz then Buzz.

Testing selection

A selection statement is only tested when every branch has run at least once. Choose test values:

  • one typical value inside each branch (for example 90, 75, 65, 55, 30);
  • every boundary: the values right at each edge, and one on each side (79, 80, 81; 69, 70, 71; ...);
  • extreme values the program should handle (0 and 100).

You will build full test plans in Lesson 15.

Just for fun

A programmer is sent to the store with this instruction: "Buy a litre of milk, and if they have eggs, buy a dozen."

He comes home with 12 litres of milk. They had eggs.

Hands-on activity

Flowchart: what should I wear?

You need: paper, a pencil, a weather app or an outdoor thermometer, and Python.

  1. Decide on 4 clothing levels, for example: below −15 °C: "parka, toque, mitts, scarf"; −15 to −1: "winter coat and toque"; 0 to 14: "light jacket"; 15 or above: "T-shirt".
  2. Draw the flowchart with a chain of decision diamonds, like the one in this lesson. Label every True and False arrow.
  3. Write the program with if/elif/else, reading the temperature with int(input(...)).
  4. Make a test table with at least 8 values: one typical value per level and the boundaries −16, −15, −1, 0, 14 and 15. Write the expected output before running.
  5. Run the tests and tick each one that matches. Finally, test today's real temperature.

What to look for: with if temp < -15:, elif temp < 0:, elif temp < 15:, else:, the boundaries give: −16 → parka; −15 → winter coat; −1 → winter coat; 0 → light jacket; 14 → light jacket; 15 → T-shirt. If any boundary gives a surprise, check < versus <=.

Your turn

1

What is printed when x = 7? When x = 12?

  • if x > 10:
  •     print("big")
  • else:
  •     print("small")
  • print("done")
2

Write an if/else that prints even or odd for an integer n.

3

What is printed for score = 65?

  • if score >= 90:
  •     print("A")
  • elif score >= 60:
  •     print("B")
  • elif score >= 50:
  •     print("C")
  • else:
  •     print("D")
4

This code has two errors. Find and fix them.

  • if age >= 16
  • print("You can apply for a G1 licence.")
5

Write a program that reads a number of centimetres of snowfall and prints Snow day! if it is 25 or more, and School is open otherwise.

6

List the test values you would use for the program in the previous question.

7

What is wrong with if mark < 0 or mark > 100: followed by print("Valid")?

More practice: warm-up

1

What punctuation mark ends an if line?

2

How many spaces should a block be indented, by convention?

3

In an if/else, how many branches run?

4

What does elif stand for?

5

What is printed when t = 0?

  • if t > 0:
  •     print("warm")
  • print("end")

More practice: on your own

1

Write a program that reads an age and prints child (under 13), teen (13 to 19) or adult (20 or over).

2

What is printed for n = 20?

  • if n > 10:
  •     print("A")
  • if n > 15:
  •     print("B")
  • else:
  •     print("C")
3

This code is meant to print exactly one level. Which marks give a wrong result? How do you fix it?

  • if mark >= 80:
  •     print("Level 4")
  • if mark >= 70:
  •     print("Level 3")
4

A store gives 10% off orders of $100 or more and free shipping on orders over $50. Write code that prints both offers when both apply. Should you use elif?

5

Draw (in words) the flowchart for an if/elif/else with two conditions.

Challenge

1

Write a program that reads three different integers and prints the largest, using only if/elif/else and and.

2

A year is a leap year if it is divisible by 4, except century years (divisible by 100), which are leap years only if divisible by 400. Write one Boolean condition, then check it for 2024, 2026, 1900 and 2000.

3

Rewrite the Ontario level chain so it gives the right answer no matter what order the branches are in.

Check your understanding

Quiz

1.

What does Python use to show which statements belong to an if?

2.

For x = 5, what does this print? if x > 3: → print("A"), elif x > 1: → print("B")

3.

Which condition order is correct for an elif chain using >= with thresholds 90, 75 and 60?

4.

Which values are best for testing if temp >= 30:?

5.

What error does a missing indent after if x > 0: cause?

6.

When should you use two separate if statements instead of if/elif?

For parents and teachers

Big idea: expectation A2.2 asks students to use sequence, selection and repetition. This lesson covers selection, with indentation as a required convention (A4.2).

How to help: turn everyday decisions into flowcharts (what to wear, what to pack for lunch). Then ask your teen "which values would you test?" A good answer always includes the boundaries.

Common difficulties:

  • Missing colons and wrong indentation.
  • Writing elif conditions in the wrong order, so an earlier branch catches values meant for a later one.
  • Using separate ifs where elif is needed (two messages print), or the reverse.
  • Off-by-one mistakes at boundaries: > versus >=.