Drop links or images here to add them to the editor.

In this topic students learn to handle a decision with three or more possible outcomes, using if, elif and else.

Learning objectives and goals

Be able to read, comprehend, trace, adapt and create Python code using selection that:

Slide deck

The slide deck for this topic is on Google Slides. A PDF copy is kept on Dodona too.

Teacher notes

These activities teach students how to use selection that outputs one of three or more different statements. The indented code below the if runs when the condition is true. elif is short for “else if”: it lets us add another condition, checked only if the previous one was false. You can add as many of these as you like, depending on how many outcomes you need. The else comes last and is used as a catch-all: if the other conditions are false, the computer skips down to the else and runs the indented code there instead.

To summarise, this code should be written like this:

if condition:
    Code to run if the condition above is true.
elif condition:
    Code to run if the condition above is true.

As many elifs as necessary (two less than the total number of outcomes: one outcome is covered by the if, another by the else).

else:
    Code to run if all conditions have been checked and found false.

You do not need to include an else at the end of a selection statement, but it is usually good practice, and there is enough cognitive load in this session already without introducing another element. I have found it useful to teach beginner students that they should always include an else.

Code examples

Weather advice for three outcomes:

if weather == "rain":
    print("Take your umbrella")
elif weather == "snow":
    print("Take your scarf")
else:
    print("No special advice for you")

Weather advice for four outcomes:

if weather == "rain":
    print("Take your umbrella")
elif weather == "snow":
    print("Take your scarf")
elif weather == "sunny":
    print("Take your sunglasses")
else:
    print("No special advice for you")

Compare two numbers:

if num1 > num2:
    print(str(num1) + " is bigger")
elif num2 > num1:
    print(str(num2) + " is bigger")
else:
    print("Numbers are the same")

Errors and misconceptions to watch out for

Make sure that students check for the following things: