To map an algorithm into Python, translate it one structure at a time: assignment, selection, loop, output. Keep the logic exactly the same and change only the notation.
This is the first lesson in Python transition and execution. It builds on the notation from pseudocode for the applicable syllabus.
How does each pseudocode piece map to Python?
| Idea | Cambridge-style pseudocode | Python |
|---|---|---|
| Store a value | Count ← 0 | count = 0 |
| Compare for equality | IF Mark = 50 | if mark == 50: |
| Other comparisons | >=, <=, <> | >=, <=, != |
| Count-controlled loop | FOR Index ← 1 TO 5 | for index in range(1, 6): |
| Loop over a list | FOR with Scores[Index] | for score in scores: |
| End of block | ENDIF, NEXT | indentation |
| Show a result | OUTPUT Count | print(count) or return count |
The range function stops one short of its second number. To count 1 to 5 you write range(1, 6).
Worked example
Algorithm: count how many of five marks are 50 or more.
Count ← 0
FOR Index ← 1 TO 5
IF Scores[Index] >= 50 THEN
Count ← Count + 1
ENDIF
NEXT Index
OUTPUT Count
Step 1, wrap it in a function. The array becomes a parameter, so the function can be tested with any list.
Step 2, translate each structure.
def count_passes(scores):
count = 0
for score in scores:
if score >= 50:
count = count + 1
return count
print(count_passes([72, 45, 50, 38, 91]))
Step 3, trace with 72, 45, 50, 38, 91.
| score | score >= 50 | count after |
|---|---|---|
| (start) | 0 | |
| 72 | True | 1 |
| 45 | False | 1 |
| 50 | True | 2 |
| 38 | False | 2 |
| 91 | True | 3 |
The output is 3. Notice that 50 counts, because the test is >= and not >.
The mistake to watch for
A frequent slip is to copy the pseudocode index range straight into Python.
Mistaken answer:
for index in range(1, len(scores)):thenscores[index]This starts at position 1, but Python lists start at position 0, so the first mark is skipped. With the list above it sees 45, 50, 38, 91 and returns 2.
The correction is to loop over the values directly, as in for score in scores, which cannot skip or overrun. If you need an index, range(len(scores)) runs from 0 to the last position. Always trace the first and last item to catch this.
Check yourself
1. Write the Python for Total ← Total + Mark.
Show answer
total = total + mark. The arrow becomes =, and the variable names are lower case by habit.
2. Write the Python condition for IF Mark = 100 THEN.
Show answer
if mark == 100:. Two equals signs compare, and the line ends with a colon.
3. What does count_passes([50, 50, 49]) return?
Show answer
2. The two 50s pass because 50 >= 50 is True, and 49 does not.
Where this leads next
Next, see how spacing changes behaviour in testing indentation and branch structure. Try the function above in the Python reasoning sandbox and compare it with the restricted pseudocode trace trainer.
If you translate correctly but lose marks on the trace, our online one-to-one Computer Science tuition can focus on exactly that habit.