Sequence, selection and iteration
Selection with if and else
Selection chooses which instructions to run by checking a condition. An if handles the first case, elseif checks another case, and else handles anything left over. The Python keywords are if, elif and else:
score = 72
IF score >= 80 THEN
OUTPUT "High"
ELSE IF score >= 50 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Try again"
ENDIF
Python uses a colon and indentation to mark each block. The conditions are checked from top to bottom, and only the first matching branch runs.
Key terms
Switch statements
A switch selects between several exact values of one expression. ERL uses switch, case and default; Python can express the same GCSE logic with if and elif:
switch day:
case "Sat":
OUTPUT "Weekend"
case "Sun":
OUTPUT "Weekend"
default:
OUTPUT "Weekday"
endswitch
Python's match is beyond this specification, so use if/elif/else for exam answers.
Key terms
For loops and ranges
A for loop repeats a known number of times. ERL's end value is included: FOR i = 0 TO 9 visits 0, 1, …, 9. Python's range stops before its end value, so range(0, 10) visits the same numbers:
FOR i = 0 TO 9
OUTPUT i
NEXT i
Both print ten values, from 0 to 9.
Common mistake
Do not copy the ERL end value straight into Python's range: range(0, 9) stops at 8. Increase the Python stop value by one to include 9.
Key terms
While and do-until loops
A while loop checks its condition before each repeat, so it may run zero times. ERL uses WHILE … ENDWHILE; Python uses while with an indented body:
answer = ""
WHILE answer != "yes"
INPUT answer
ENDWHILE
ERL's DO … UNTIL checks after the body, so it always runs at least once. Python can copy that behaviour with while True and a break when the stopping condition is met:
DO
INPUT answer
UNTIL answer == "yes"
A trace table records values after each step. For total = 0 followed by for i in range(1, 4): total = total + i, the rows are:
| i | total |
|---|---|
| 1 | 1 |
| 2 | 3 |
| 3 | 6 |
The final output is 6.