Programming · Actions
up to +100 XP
Stop 2.6 · Programming · 3 min

Actions

Master control structures and program flow

Learning objectives:
  • Know sequence, selection and iteration and when each is used (2.6.1–2.6.4)
  • Know the benefits and drawbacks of loops (2.6.5)
  • Interpret, develop and debug code using actions (2.6.6–2.6.8)

Sequence

Instructions run one after another, in the order they are written. Sequence matters: calculating a total before the values are input gives the wrong answer.

Selection

Selection chooses which code runs, based on a condition.

if temperature > 25:
    print("Hot")
elif temperature > 15:
    print("Mild")
else:
    print("Cold")

match/case compares one value against several possible cases. It is neat when there are many fixed options, such as menu choices.

match choice:
    case "1":
        print("New booking")
    case "2":
        print("Cancel booking")
    case _:
        print("Invalid option")

case _ catches anything that did not match.

Iteration (loops)

Count-controlled loop: for

Repeats a set number of times, or once for each item in a collection.

for i in range(1, 6):
    print(i)          # 1 to 5

Condition-controlled loop: while

Repeats while a condition is True. Use it when you don't know in advance how many times to repeat, such as asking until the input is valid.

pin = input("PIN: ")
while pin != "1234":
    pin = input("Wrong. Try again: ")

Benefits and drawbacks of loops

BenefitsDrawbacks
Less code, so fewer mistakes and easier maintenanceA wrong condition can cause an infinite loop
Can process any amount of dataOff-by-one errors are easy to make (range(1, 5) stops at 4)
Makes repeated tasks consistentNested loops can be slow and hard to read

Common action bugs

Quick check · 11 questions · up to 100 XP

Check what stuck.

+10 XP each
Question 1

Question 1 of 11

Which action runs instructions one after another in order?

Question 2

Question 2 of 11

Which keyword in Python means "else if"?

Question 3

Question 3 of 11

What is match/case useful for?

Question 4

Question 4 of 11

What does case _: do in a match statement?

Question 5

Question 5 of 11

Which loop is count-controlled?

Question 6

Question 6 of 11

When is a while loop most suitable?

Question 7

Question 7 of 11

How many times does for i in range(1, 5): run?

Question 8

Question 8 of 11

What is a drawback of loops?

Question 9

Question 9 of 11

Grades are checked with if score >= 40 first, then elif score >= 70. What goes wrong?

Question 10

Question 10 of 11 · Match the pairs

Match each construct to its meaning.

Sequence
Selection
Count-controlled loop
Condition-controlled loop
Question 11

Question 11 of 11 · Coding

Write grade(score): return "Distinction" for 70 or more, "Merit" for 60 to 69, "Pass" for 40 to 59, otherwise "Fail".

Open the IDE
Hint

Use if / elif / else, checking the highest grade first.