OCR GCSE COMPUTER SCIENCE · J277 · PAPER 2
Selection and iteration
Choose which code runs, and repeat it. If, switch, for, while and do until.
Paper 2 · Lesson 23
OCR GCSE COMPUTER SCIENCE · J277 · PAPER 2
Selection and iteration
Choose which code runs, and repeat it. If, switch, for, while and do until.
Paper 2 · Lesson 23
Lesson 23 of the J277 series (Block D, Paper 2, sections 2.2.1 and 2.2.2 Programming fundamentals): the three programming constructs, selection and iteration.
Cover photo: Walter O / Unsplash (hologram of railway points: one track splits into two, like a program at an if statement).
Device-free: show the slide; pupils write the title and date. Image credit: Walter O / Unsplash (cover hologram)
00 · MISSION · BY THE END OF THIS LESSON
By the end of this lesson you can…
01 Name the three programming constructs and say what each one does.
02 Write selection with if, elseif, else, nested if and switch/case.
03 Choose, write and trace count-controlled and condition-controlled loops.
Read the three outcomes. J277 section 2.2 expects pupils to know and use the three basic programming constructs (sequence, selection and iteration), including count-controlled and condition-controlled loops, in OCR Exam Reference Language or a high-level language such as Python.
Device-free: pupils copy the outcomes and tick each one at the end.
02 · CHECK · DO NOW (LESSON 22)
Warm up: variables and data types
1 Which data type should store the phone number "07700 900123"?
2 What does int() do?
3 What is 17 MOD 5?
4 What is 17 DIV 5?
▮ TERMINAL // do_now_answers
1 string: it starts with 0,
has a space, no maths on it
2 casts a value to an integer:
int("15") gives 15
3 2 (the remainder)
4 3 (whole times 5 goes in)
Retrieval from lesson 22. Give 4 minutes, then click to reveal the answers line by line.
1 String. An integer would lose the leading 0, cannot hold the space, and nobody does maths on a phone number. 2 int() casts (converts) a value to an integer, for example int("15") gives the integer 15; it is used with input(), which always returns a string. 3 17 MOD 5 = 2: 5 goes into 17 three times (15), remainder 2. 4 17 DIV 5 = 3: the whole number of times 5 goes into 17.
Device-free: questions on the board; mini whiteboards.
Recap. A program stores whether a door is locked. Which data type fits best?
Boolean
Character
Integer
String
Answer: A, Boolean. A door is either locked or not, so the value is only ever True or False.
A string such as "yes" would work but is not the most suitable type. Integer and character do not fit a yes/no value. Today this matters because every if statement and every loop is controlled by a Boolean condition: something that is either True or False.
Photo: Kaffeebart / Unsplash.
Device-free: students hold up A, B, C or D cards. Image credit: Kaffeebart / Unsplash
01 · LEARN · MISSION BRIEFING
Control the flow
Every program is built from just three programming constructs. Today you meet all three.
SEQUENCE
Lines run in order, one after another.
SELECTION
A condition chooses which code runs: if, switch.
ITERATION
Code is repeated in a loop: for, while, do until.
SYSTEM VOICE
System online. Today's mission: control the flow. Learn the three programming constructs, make decisions with if and switch, repeat code with for and while loops, and trace a loop line by line.
Click play for the system voice briefing. The words are also on the slide.
Sequence: the program runs each line in order, top to bottom. Selection: a condition (True or False) decides which block of code runs. Iteration: a block of code is repeated. Every program, from a calculator to a game, is built from these three.
Quick hook: a game checks every frame whether the player has hit an enemy (selection) and keeps running the game loop until the player quits (iteration).
Device-free: pupils write one everyday example of each construct (for example: a recipe's steps, "if it rains take a coat", "stir 10 times").
01 · LEARN · SELECTION
if, elseif, else
▮ TERMINAL // grades.erl
1 mark = int(input("Mark? "))
2 if mark >= 70 then
3 print("Distinction")
4 elseif mark >= 50 then
5 print("Merit")
6 elseif mark >= 40 then
7 print("Pass")
8 else
9 print("Fail")
10 endif
▮ TERMINAL // trace two inputs
> Mark? 65
65 >= 70 False
65 >= 50 True
> Merit
> Mark? 38
38 >= 70 False
38 >= 50 False
38 >= 40 False
> Fail (else)
Only the first True branch runs. Order matters: test the highest boundary first.
Selection: a condition decides which block of code runs. The program in OCR Exam Reference Language (ERL) gives a grade from a mark.
Click to trace two inputs. Mark 65: line 2, 65 >= 70 is False, so skip to line 4; 65 >= 50 is True, so line 5 runs and displays Merit. Then the program jumps straight to endif: line 6 is never tested, even though 65 >= 40 is also True. Mark 38: 38 >= 70 False, 38 >= 50 False, 38 >= 40 False, so the else branch runs and displays Fail.
Why order matters: if the program tested mark >= 40 first, a mark of 85 would display Pass, because that would be the first True branch.
else has no condition: it catches everything that did not match. elseif and else are both optional.
Device-free: pupils trace the program for 70 (Distinction: >= includes 70) and 49 (Pass).
01 · LEARN · PYTHON AND NESTED IF
The same idea in Python, and an if inside an if
▮ TERMINAL // grades.py
1 mark = int(input("Mark? "))
2 if mark >= 70:
3 print("Distinction")
4 elif mark >= 50:
5 print("Merit")
6 elif mark >= 40:
7 print("Pass")
8 else:
9 print("Fail")
▮ TERMINAL // nested.erl
1 if age >= 17 then
2 if passedTest == "yes" then
3 print("You can drive")
4 else
5 print("Pass your test first")
6 endif
7 else
8 print("Too young")
9 endif
Python: elif, a colon and an indent instead of then and endif. Nested if: the inner if is only tested when the outer one is True.
Left: the grade program from the last slide in Python. It behaves exactly the same: 65 displays Merit and 38 displays Fail (both run in Python 3). Python writes elif, not elseif, ends each condition with a colon, and uses indentation instead of then and endif. In the exam, OCR accepts ERL or a high-level language such as Python.
Right: a nested if is an if statement inside another one. Trace age 18, passedTest "no": 18 >= 17 is True, so the inner if is tested; "no" == "yes" is False, so the inner else runs: Pass your test first. Trace age 15, passedTest "yes": 15 >= 17 is False, so the outer else runs straight away: Too young. The inner if is never tested.
Each if needs its own endif in ERL. Indent the inner if so the pairs are easy to see.
Device-free: pupils trace the nested program for age 17 and passedTest "yes" (You can drive).
01 · LEARN · SWITCH/CASE
One variable, many cases
▮ TERMINAL // weekend.erl
1 switch day:
2 case "Sat":
3 print("Weekend")
4 case "Sun":
5 print("Weekend")
6 default:
7 print("School day")
8 endswitch
▮ TERMINAL // weekend.py
1 if day == "Sat":
2 print("Weekend")
3 elif day == "Sun":
4 print("Weekend")
5 else:
6 print("School day")
day = "Sun" matches case "Sun": Weekend. day = "Mon" matches no case, so default runs: School day.
Python uses if, elif and else for this.
switch/case is selection on one variable: the program compares day with each case in turn and runs the code under the first one that matches. default works like else: it runs when no case matches.
Trace day = "Sun": not "Sat", matches "Sun", displays Weekend. Trace day = "Mon": matches no case, so default displays School day. The Python version on the right gives the same outputs (checked in Python 3).
OCR ERL syntax: switch variable: / case value: / default: / endswitch. Python uses if/elif/else for this in the GCSE course. (Newer Python versions also have match, but it is not needed for J277.)
When to use switch: many fixed values of one variable, such as a menu choice. Use if/elseif for ranges such as mark >= 70.
Device-free: pupils write a switch for a menu: case "1" prints Play, case "2" prints Settings, default prints Invalid choice.
01 · LEARN · COUNT-CONTROLLED ITERATION
for loops repeat a set number of times
▮ TERMINAL // count.erl
for i = 1 to 5
print(i)
next i
> 1 2 3 4 5
for i = 1 to 10 step 2
print(i)
next i
> 1 3 5 7 9
▮ TERMINAL // count.py
for i in range(1, 6):
print(i)
> 1 2 3 4 5
for i in range(1, 11, 2):
print(i)
> 1 3 5 7 9
ERL: to 5 includes 5. Python: range(1, 6) stops before 6, so it gives 1 to 5.
Each number is printed on its own line. range(10) gives 0 to 9, like for i = 0 to 9.
Count-controlled iteration: the loop runs a fixed number of times, counted by a variable (here i).
ERL, left: for i = 1 to 5 ... next i runs with i = 1, 2, 3, 4, 5. The end value 5 IS included. step 2 adds 2 each time: 1, 3, 5, 7, 9; the next value, 11, is past 10, so the loop stops.
Python, right (click to compare): range(start, stop) STOPS BEFORE the stop value, so range(1, 6) gives 1, 2, 3, 4, 5. To match ERL "1 to 10 step 2", Python needs range(1, 11, 2): 1, 3, 5, 7, 9. range(10) on its own starts at 0 and gives 0 to 9, ten numbers, the same as ERL for i = 0 to 9. All outputs checked in Python 3; print puts each number on its own line.
Counting down: ERL for i = 3 to 1 step -1 and Python range(3, 0, -1) both give 3, 2, 1.
Misconception: range(1, 5) does NOT include 5. Pupils lose marks for off-by-one errors.
Device-free: pupils write the ERL and Python loops that print 2, 4, 6, 8, 10 (for i = 2 to 10 step 2; range(2, 11, 2)).
01 · LEARN · CONDITION-CONTROLLED ITERATION
while or do until?
▮ TERMINAL // while.erl
1 count = 10
2 while count <= 5
3 print(count)
4 count = count + 1
5 endwhile
> (nothing is printed)
▮ TERMINAL // do_until.erl
1 count = 10
2 do
3 print(count)
4 count = count + 1
5 until count > 5
> 10
while checks the condition first, so it can run 0 times.
do ... until checks at the end, so it always runs at least once.
Python has while (while count <= 5:) but no do ... until.
Condition-controlled iteration: the loop keeps going until a condition changes, so the number of repeats is not known in advance.
Both programs start with count = 10. Left, while: line 2 checks count <= 5 BEFORE the body. 10 <= 5 is False, so the body never runs and nothing is printed (checked in Python 3 with while count <= 5:). Right, do ... until: the body runs first, printing 10 and making count 11; then line 5 checks count > 5, which is True, so the loop stops. Output: 10, once.
Key difference: while loops while the condition is True; do ... until loops until the condition becomes True. A do ... until always runs at least once, which suits "ask, then check" tasks such as a password prompt.
Infinite loops: if nothing inside the loop changes count, a while loop that starts True never ends.
Device-free: pupils change count = 10 to count = 3 and trace both loops (both print 3, 4, 5).
01 · LEARN · TRACING A LOOP
Trace it one pass at a time
▮ TERMINAL // total.erl
1 total = 0
2 for i = 1 to 4
3 total = total + i
4 next i
5 print(total)
One row per pass. Write a value only when it changes.
Python: for i in range(1, 5) runs i = 1, 2, 3, 4, the same as for i = 1 to 4.
▮ TERMINAL // trace_table
i | total | output
---+-------+-------
- | 0 |
1 | 1 |
2 | 3 |
3 | 6 |
4 | 10 |
| | 10
A trace table records the value of each variable as the program runs, one row per pass of the loop. Click to fill it in row by row, asking pupils for each value first.
Line 1: total = 0, i has no value yet. Pass 1: i = 1, total = 0 + 1 = 1. Pass 2: i = 2, total = 1 + 2 = 3. Pass 3: i = 3, total = 3 + 3 = 6. Pass 4: i = 4, total = 6 + 4 = 10. i = 4 is the last value (to 4 includes 4), so the loop ends and line 5 outputs 10. Checked in Python 3 with for i in range(1, 5): the output is 10.
Exam tip: the output column is only filled in on the row where something is printed.
Device-free: pupils copy the table and trace the same program with to 5 instead (total 15).
01 · LEARN · THE BIG IDEA
Selection is a fork in the path
1 The fork is the condition: True or False?
2 Each path is a branch of code.
3 Only one path is taken each time.
4 elseif adds more paths. else is the path when nothing else matches.
5 A loop is a path that leads back to the same check.
Remember: selection chooses a path, iteration repeats one.
Click to reveal the points. The picture is the idea to remember: one path splits into two, and a walker can only take one of them. That is exactly what an if statement does: the condition is checked at the fork, and the program follows one branch only.
elseif adds more forks further along; else is the path for everyone who did not turn off earlier. A loop is different: it is a path that brings you back to the same fork again and again until the condition sends you on.
Photo: Jens Lelie / Unsplash.
Device-free: pupils draw the fork and label it with the grade program: condition mark >= 70 at the fork, Distinction on one path, the next check on the other. Image credit: Jens Lelie / Unsplash
01 · LEARN · CHOOSING A LOOP
Which loop for the job?
FOR
You know how many times. Count-controlled.
Print 10 names.
WHILE
Repeat while a condition is True. Checks first: may run 0 times.
Play while lives > 0.
DO ... UNTIL
Repeat until a condition is True. Checks last: runs at least once.
Ask for a PIN.
SYSTEM VOICE · KEY DEFINITION
Selection runs a block of code only when a condition is true. Iteration repeats a block of code. A count-controlled loop repeats a set number of times. A condition-controlled loop repeats until a condition is met.
Play the key definition, then go through the three cards.
For loop (count-controlled): use when the number of repeats is known before the loop starts, such as 10 names or 12 rows of a times table. While loop (condition-controlled): checks the condition before each pass, so if it is False at the start the body never runs; use it when the number of repeats is unknown, such as a game that runs while lives > 0. Do ... until (condition-controlled): checks after each pass, so the body always runs at least once; ideal for asking for input and then checking it, such as a PIN.
Exam wording: "count-controlled" = for; "condition-controlled" = while or do ... until.
Device-free: pupils write one new example of their own for each loop.
Which construct fits each task best?
FOR LOOP
WHILE LOOP
IF STATEMENT
Keep asking until a valid age is typed
Show Child or Adult from an age
Run the game while lives are above 0
Give a discount only if the total is over £50
Ask for exactly 5 test scores
Print the 7 times table from 1 to 12
Answers. For loop: ask for exactly 5 test scores; print the 7 times table from 1 to 12 (the number of repeats is known). While loop: keep asking until a valid age is typed; run the game while lives are above 0 (the number of repeats is not known). If statement: show Child or Adult from an age; give a discount only if the total is over £50 (a choice made once, nothing is repeated).
Ask: could "keep asking until a valid age is typed" also be a do ... until? (Yes: it asks at least once, so do ... until fits well too. In Python it is a while loop.)
Device-free: pupils draw three columns and write each task in the right one.
A runner's laps are counted with for lap = 0 to 9. How many times does the loop run?
9
8
11
10
Answer: D, 10. In ERL, for lap = 0 to 9 includes both ends: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. That is ten values, so ten passes. The Python version is for lap in range(10), which also gives 0 to 9, ten numbers (checked in Python 3).
9 is the common wrong answer: counting 9 - 0 and forgetting the 0. 11 would be 0 to 10. 8 has no sensible reason.
Photo: isaiah best / Unsplash.
Device-free: students hold up A, B, C or D cards. Image credit: isaiah best / Unsplash
A keypad must ask for a PIN at least once. Which always runs its code at least once?
while ... endwhile
do ... until
for ... next
if ... endif
Answer: B, do ... until. The condition is checked at the END of each pass, so the body (ask for the PIN) always runs at least once.
A while loop checks first, so it could run 0 times. A for loop runs a fixed number of times, which does not suit "keep asking until the PIN is right". if ... endif is selection, not a loop: it never repeats.
Photo: Rich Smith / Unsplash.
Device-free: students hold up A, B, C or D cards. Image credit: Rich Smith / Unsplash
03 · DEBUG · SPOT THE MISTAKE
One comment in Zainab's code is wrong
▮ TERMINAL // zainab_loops.py
1 for i in range(3): print(i) # 0 1 2
2 for i in range(1, 5): print(i) # 1 2 3 4 5
3 for i in range(0, 10, 2): print(i) # 0 2 4 6 8
4 for i in range(5, 0, -1): print(i) # 5 4 3 2 1
Run each loop in your head. Then tap the marker.
Tip: range(start, stop, step) never includes the stop value.
Give a minute to find the mistake before tapping the marker. The comments (after #) are Zainab's notes on what each loop prints; each number really appears on its own line.
Answer: line 2. range(1, 5) stops BEFORE 5, so it prints 1, 2, 3, 4. To print 1 to 5 it must be range(1, 6), the same as ERL for i = 1 to 5. The other lines are correct (all four run in Python 3): range(3) gives 0, 1, 2; range(0, 10, 2) gives 0, 2, 4, 6, 8; range(5, 0, -1) counts down 5, 4, 3, 2, 1 and stops before 0.
Device-free: copy the four lines onto the board; pupils write the wrong line number and the correct output.
Put the steps of a while loop in the order they happen.
Correct order: 1 give the loop variable a starting value; 2 check the condition; 3 if it is True, run the code inside the loop; 4 change the variable inside the loop; 5 go back and check the condition again; 6 when it is False, carry on after endwhile.
In code: count = 1 (step 1), while count <= 3 (steps 2 and 5), print(count) (step 3), count = count + 1 (step 4), endwhile then the next line (step 6). Step 4 matters: without it the condition never changes and the loop never ends (an infinite loop).
Device-free: pupils write the six steps on sticky notes and order them on the desk.
Complete the summary.
The three programming constructs are sequence, selection and iteration. A for loop is count-controlled. A while loop checks its condition first, so it may never run. A do ... until loop always runs at least once. In Python, range(1, 6) gives the numbers 1 to 5.
Answers in order: selection, iteration, for, while, until, 5. Distractors: if, endif, 6.
6 is the classic off-by-one error: range(1, 6) stops before 6. if is an example of selection, not the name of the construct.
Device-free: paragraph on the board with gaps and the word bank; pupils write the six missing words.
EXAM · Write an algorithm that asks for a password until the user enters Orange42, then outputs Access granted. [4 marks]
Exam-style question, 4 marks. Give 5 minutes. Pupils may answer in OCR Exam Reference Language or Python. The model answer is on the next slide.
Mark scheme: 1 mark each. Asks the user to input a password. Uses a condition-controlled loop (while or do ... until). Loop stops only when the password is "Orange42", with the input repeated inside the loop. Outputs "Access granted" after the loop ends.
Do not award the loop mark for an if statement on its own: it only checks once. A for loop does not fit, because the number of attempts is not known.
Device-free: pupils answer on paper, then peer-mark with the next slide.
04 · EXAM · MODEL ANSWER
Ask until it is right
▮ TERMINAL // password.erl
1 password = input("Password? ")
2 while password != "Orange42"
3 password = input("Password? ")
4 endwhile
5 print("Access granted")
or, with do ... until:
do
password = input("Password? ")
until password == "Orange42"
print("Access granted")
MARK SCHEME
1 mark: input a password
1 mark: condition-controlled loop
1 mark: repeats until "Orange42"
1 mark: outputs "Access granted" after the loop
Python is also accepted.
Click to reveal the model answer line by line. Trace it with inputs abc, orange42, Orange42: abc != "Orange42" is True, so ask again; orange42 is also different (capital O matters), so ask again; Orange42 makes the condition False, the loop ends and Access granted is displayed.
The do ... until version (bottom of the terminal) is just as good: the input is inside the loop, and it always runs at least once.
Python version (also accepted; tested in Python 3 with the three inputs above): the same four lines, with while password != "Orange42": ending in a colon, the second input indented underneath it, no endwhile, and print("Access granted") back at the left margin.
Common mistakes: no input inside the loop (an infinite loop), using if instead of a loop, or putting the print inside the loop.
Device-free: pupils tick each mark-scheme point on their own answer and correct it in a different colour.
How sure are you about loops?
Very: I can choose and trace loops
Fairly: range() still trips me up
Not yet: I need another go
Anonymous exit poll. If many pupils find range() tricky, start lesson 24 by tracing for i in range(...) loops with different start, stop and step values, since lesson 24 loops through strings and arrays.
Device-free: thumbs up, sideways or down.
05 · NEXT · KEEP GOING
Keep going
Isaac Computer Science
Free online lessons and questions. Look for the topics on selection and iteration.
BBC Bitesize
GCSE Computer Science, OCR: revise programming constructs and loops.
Try it in Python
Ask for a number, then use a for loop to print its times table from 1 to 12.
Next lesson: strings, arrays and records.
Point pupils to the places to practise. Isaac Computer Science and BBC Bitesize are free.
The Python challenge, as a model: n = int(input("Number? ")) then for i in range(1, 13): print(str(i) + " x " + str(n) + " = " + str(i * n)). Typing 7 displays 1 x 7 = 7 up to 12 x 7 = 84. Note range(1, 13) to include 12.
Device-free: pupils write the program on paper and trace the first three lines of output for 7, to bring to lesson 24.