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
| Benefits | Drawbacks |
|---|---|
| Less code, so fewer mistakes and easier maintenance | A wrong condition can cause an infinite loop |
| Can process any amount of data | Off-by-one errors are easy to make (range(1, 5) stops at 4) |
| Makes repeated tasks consistent | Nested loops can be slow and hard to read |
Common action bugs
- Steps in the wrong order.
elifconditions in the wrong order, so a broad condition catches values first (check the highest grade first).- A
whileloop whose variable never changes, so it never ends.