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

Free lesson

2.6 (1 of 3): Sequence and selection

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The bus reader makes a choice

You tap your card on the bus. The reader asks itself some questions. Is this a child? Is this a student? Is it after 9am?

Each answer changes the price. A program does the same. It follows steps in order. At some steps it makes a choice. In this lesson you learn both.

Key words

WordWhat it meansExample
SequenceSteps that run one after another, from the top to the bottom.print, then print
SelectionA choice. The program picks one path.if age < 16
ConditionA question with the answer True or False.age < 16
ifRuns its lines only when the condition is True.
elifShort for else if. It tests another condition when the ones above were False.
elseRuns when no condition above was True.
match caseCompares one value with a list of patterns and picks the first that fits.
IndentationThe spaces at the start of a line. They show which lines belong inside the if.
FlowchartA picture of steps and decisions, drawn with symbols and arrows.

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

Sequence: one step after another

A sequence is a list of steps that run in order. Python starts at the top and goes down. It does not skip a line unless you ask it to.

Order matters. You cannot take your ticket before you tap your card.

Try it: steps in order

Code: python
print("1. Tap your card")
print("2. The reader checks the fare")
print("3. Take your ticket")

# Swap line 1 and line 3, then run it again.
# The steps still run in order. But now the order is wrong.

Make a free account to save your work and track your progress.

Quick check: sequence

Have a go

Quick check: sequence

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Selection: the program chooses

Selection means the program chooses a path. It looks at a condition. A condition is a question with the answer True or False.

If the answer is True, one path runs. If it is False, the program takes the other path.

The child fare as a flowchart

flowchart TD
  start(["Start"]) --> getAge[/"Input the age"/]
  getAge --> check{"Is age less than 16?"}
  check -->|"True"| child["Fare is 1.00"]
  check -->|"False"| adult["Fare is 2.50"]
  child --> show[/"Output the fare"/]
  adult --> show
  show --> stop(["End"])

Flowchart symbols

SymbolWhat it means
Rounded boxStart or end
RectangleA process: something to do
Rectangle with double sidesA sub-process: a part that has its own flowchart
DiamondA decision: a question with two or more ways out
ParallelogramInput or output
Small circleA connector: joins to another part of the chart
ArrowThe flow: which step comes next

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

Try it: if and else

Code: python
age = 14
if age < 16:
    print("Child fare: 1.00")
else:
    print("Adult fare: 2.50")

# Change age to 30 and run it again.

Make a free account to save your work and track your progress.

Symbols that compare

SymbolMeaningExampleResult
<less than3 < 5True
>more than3 > 5False
<=less than or equal to5 <= 5True
>=more than or equal to4 >= 5False
==equal to5 == 5True
!=not equal to5 != 5False

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

Many paths: elif

Use elif when there are more than two paths. Python checks the conditions from the top. It runs the first one that is True. Then it skips the rest.

The order matters. Test the smallest ages first. If you test age < 16 before age < 5, a 3-year-old pays the child fare, not the free fare. The else at the end catches everything left.

Try it: four fares

Code: python
age = 70
if age < 5:
    print("Free")
elif age < 16:
    print("Child fare")
elif age >= 65:
    print("Senior fare")
else:
    print("Adult fare")

# Try the ages 3, 10, 40 and 70.

Make a free account to save your work and track your progress.

Trace table: which path runs?

ageage < 5age < 16age >= 65Output
3Truenot askednot askedFree
10FalseTruenot askedChild fare
40FalseFalseFalseAdult fare
70FalseFalseTrueSenior fare

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

A common mistake: = is not ==

Warning

Many people use = in a condition. A single = stores a value. == compares two values, so use it when you ask a question. Also put a colon : at the end of the if line. Indent the lines inside by the same amount, usually 4 spaces.

Match the code to its meaning

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Watch: which lines run

Press Play on the short film below. It runs code like the code above and numbers each line in the order it runs. A line with no number is skipped. Watch how many paths run, and what the spaces at the start of a line decide.

Film: sequence and selection

Sequence and selection

Every scene, as text

  1. Python runs the lines in order, from the top to the bottom: that is sequence. At the if line, it picks one path: that is selection. age is 14, so the condition age < 16 is True and the line indented under if runs, printing Child fare: 1.00. The else path is skipped.
  2. Myth (false): every branch that is True runs. Here age < 16 is tested before age < 5. For 3 it is True, so Child fare prints and Python skips the rest: age < 5 is True too, but it is never asked. A 3-year-old pays the child fare.
  3. The cure is the lesson's order: test the smallest ages first. Now age < 5 is asked first. It is True, so Free prints and the rest are not asked. With if, elif and else, exactly one path runs.
  4. For 40, Python asks each condition in turn, from the top. elif, short for else if, is only asked when everything above was False. age < 5, age < 16 and age >= 65 are all False, so else runs, printing Adult fare. else runs when no condition above was True.
  5. Indentation, the spaces at the start of a line, shows which lines belong to a path. For 30, age < 16 is False, so the line indented under if is skipped and the line indented under else runs. print("3. Take your ticket") has no spaces, so it belongs to neither path and runs either way.

Another way: match case

match case compares one value with several patterns. It suits exact values, like days of the week or a menu number.

The pattern _ means anything else, like else.

Try it: match case

Code: python
day = "Sat"
match day:
    case "Sat":
        print("Weekend: a bus every 30 minutes")
    case "Sun":
        print("Weekend: a bus every 30 minutes")
    case _:
        print("Weekday: a bus every 10 minutes")

# Change day to "Tue" and run it again.

Make a free account to save your work and track your progress.

Extra: Try it: two values, one case

Code: python
day = "Sun"
match day:
    case "Sat" | "Sun":
        print("Weekend: a bus every 30 minutes")
    case _:
        print("Weekday: a bus every 10 minutes")

# The sign | means or. One case now covers Sat and Sun.
# The answer is the same as the code above.

Make a free account to save your work and track your progress.

Your turn: the fare chooser

Finish two functions.

  1. fare(age) gives back the price for an age: 0.0 under 5, 1.0 under 16, 1.5 for 65 or over, and 2.5 for everyone else. Use if, elif and else.
  2. day_type(day) uses match case: "Sat" and "Sun" give back "weekend". Any other day gives back "weekday".

Press Run Tests to check.

Code: python
def fare(age):
    # Under 5 travel free: give back 0.0.
    # Under 16 pay 1.0. Aged 65 or over pay 1.5.
    # Everyone else pays 2.5.
    return None


def day_type(day):
    # Use match case.
    # "Sat" or "Sun" give back "weekend".
    # Any other day gives back "weekday".
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Your turn: finish the flowchart

Finish the flowchart for the four fares. Under 5 is free. Under 16 pays 1.00. 65 or over pays 1.50. Everyone else pays 2.50. Add a diamond for each decision and a rectangle for each fare. Every path must reach the Output box and then End. Your teacher will check it.

flowchart TD
  start(["Start"]) --> getAge[/"Input the age"/]
  getAge --> under5{"Is age less than 5?"}
  under5 -->|"True"| free["Fare is 0.00"]
  under5 -->|"False"| more{"Add the next decision here"}
  free --> show[/"Output the fare"/]
  show --> stop(["End"])

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.