All GCSE 1 30 min read 10 question quiz 15 exam marks

Exam Pseudocode to Python

Every exam board prints algorithms in its own pseudocode. Every construct it uses, next to the Python that does the same job, with the traps where they differ.

Reading exam pseudocode

OCR prints algorithms in its Exam Reference Language (ERL). AQA prints its own pseudocode. Edexcel's Paper 2 is sat on a computer, in Python itself. The ideas are identical. Only the spelling differs, and the exam is easier once you can translate without thinking.

IdeaOCR reference languageAQA pseudocodePython
Assign a valuex = 5x ← 5x = 5
Outputprint("Hi")OUTPUT "Hi"print("Hi")
Inputname = input("Name? ")name ← USERINPUTname = input("Name? ")
Count loopfor i = 1 to 5 ... next iFOR i ← 1 TO 5 ... ENDFORfor i in range(1, 6):
Loop, test firstwhile x < 10 ... endwhileWHILE x < 10 ... ENDWHILEwhile x < 10:
Loop, test lastdo ... until x >= 10REPEAT ... UNTIL x >= 10while True: then break
Selectionif elseif else endifIF ELSE IF ELSE ENDIFif elif else
Subprogramfunction or procedureSUBROUTINEdef

The loop that costs the most marks

Python
# for i = 1 to 5
#     print(i)
# next i
for i in range(1, 6):
    print(i)              # 1 2 3 4 5, one per line
The stop value is one past the last number

In the exam for i = 1 to 5 runs for 1, 2, 3, 4 and 5. In Python range(1, 5) stops at 4, so the Python for that loop is range(1, 6). Whenever you translate a count loop, write down the last value you want and add one.

Exam loops and rangeThree exam loops beside their Python. For i equals 1 to 5 is range 1, 6: the loop runs for 1, 2, 3, 4 and 5, and the stop value 6 is not used. For i equals 0 to 20 step 5 is range 0, 21, 5: the loop runs for 0, 5, 10, 15 and 20, and 21 is not used. For i equals 10 to 1 step minus 3 is range 10, 0, minus 3: the loop runs for 10, 7, 4 and 1, and the stop value 0 is not used. The stop value is always one past the last wanted number in the direction of counting.The exam loop and the Python that matches itfor i = 1 to 5range(1, 6)123456stop: never includedthe loop runs for thesefor i = 0 to 20 step 5range(0, 21, 5)0510152021stop: never includedthe loop runs for thesefor i = 10 to 1 step -3range(10, 0, -3)107410stop: never includedthe loop runs for theseThe stop value is always one past the last number you want, in whichever direction the loop counts.
Write down the last value you want, then move one step past it.

A step is the third value in range:

Python
# for i = 0 to 20 step 5
for i in range(0, 21, 5):
    print(i, end=" ")     # 0 5 10 15 20
print()

Counting down needs a negative step, and the stop value is still one past the end, in the direction you are going:

Python
# for i = 10 to 1 step -3
for i in range(10, 0, -3):
    print(i, end=" ")     # 10 7 4 1
print()

Loop, test last

Python has no do ... until. The body must run at least once and the test comes at the bottom, so you build it from a loop that never ends on its own and a break:

Python
# do
#     total = total + 7
# until total > 30
total = 0
while True:
    total = total + 7
    if total > 30:
        break
print(total)              # 35

The condition is the one you stop on. until total > 30 becomes if total > 30: break. Do not flip it into the loop header unless you also set up the variable first:

Python
total = 7
while total <= 30:
    total = total + 7
print(total)              # 35

That version gives the same answer, but only because the variable was primed to the value the first pass would have produced. The while True form is safer, because it cannot be wrong that way.

Selection with many branches

OCR reference language
switch day:
    case "Sat":
        print("Weekend")
    case "Sun":
        print("Weekend")
    default:
        print("Weekday")
endswitch
Python
day = "Sat"
if day == "Sat" or day == "Sun":
    print("Weekend")
else:
    print("Weekday")

Python 3.10 added match, which reads more like the exam's switch. The | means "or" and _ is the default:

Python
day = "Sat"
match day:
    case "Sat" | "Sun":
        print("Weekend")
    case _:
        print("Weekday")

Data types, casting and operators

The exam names five data types. Python has four of them, because it has no separate character type.

Exam namePython typeExample
Integerint42
Realfloat3.14
BooleanboolTrue
Characterstr of length one"A"
Stringstr"Computing"
Python
print(type(7), type(7.0), type(True), type("7"), type("A"))
# <class 'int'> <class 'float'> <class 'bool'> <class 'str'> <class 'str'>

Casting

Casting converts a value from one type to another. input always gives back a string, so anything you want to calculate with must be cast first.

Python
age_text = "15"
print(int(age_text) + 1)     # 16
print(str(15) + "!")         # 15!
print(float("2.5") * 2)      # 5.0
print(int(7.9))              # 7
print(round(7.9))            # 8

int(7.9) throws the decimal part away, giving 7. round(7.9) rounds, giving 8. They are different operations, and an exam question about a price or an average will care which one you meant.

Casting a string to a bool is almost always true

bool("False") is True, because any string with something in it counts as true. Only the empty string "", the number 0 and None give False.

Python
print(bool(0), bool(1), bool(""), bool("False"))     # False True False True

MOD, DIV and exponent

ExamMeaningPython17 and 5 give
+ - *add, subtract, multiply+ - *22 12 85
/real division/3.4
DIVwhole number division//3
MODremainder%2
^to the power of**1419857
In Python, ^ is not "to the power of"

It is the bitwise XOR operator. 2 ** 3 is 8 but 2 ^ 3 is 1. If a translation of an exam ^ gives you a strange small number, this is the reason.

Python
print(17 / 5, 17 // 5, 17 % 5)     # 3.4 3 2
print(2 ** 3)                      # 8
print(2 ^ 3)                       # 1, which is XOR

MOD and DIV are exam favourites because one pair of lines splits a quantity into units:

Python
total_seconds = 3725
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
print(hours, "h", minutes, "m", seconds, "s")     # 1 h 2 m 5 s

Learn the five uses of MOD, because the question rarely says "use MOD":

To find outWrite
Is n even?n % 2 == 0
Is n a multiple of 3?n % 3 == 0
What is the last digit of n?n % 10
What is n without its last digit?n // 10
Wrap round after a limit (clock, alphabet)(position + shift) % 26

Boolean operators

not binds tightest, then and, then or. Brackets make the intention clear and change the result:

Python
a, b, c = True, False, False
print(a or b and c)         # True, because and goes first: a or (b and c)
print((a or b) and c)       # False
print(not a or b)           # False, because not goes first: (not a) or b

Text handling

ExamPython
name.lengthlen(name)
name.substring(2, 3)name[2:5]
name.left(3)name[:3]
name.right(3)name[-3:]
name.upper and name.lowername.upper() and name.lower()
ASC("A")ord("A")
CHR(65)chr(65)
Python
word = "Computing"
print(len(word))                     # 9
print(word[2:5])                     # mpu
print(word[:3], word[-3:])           # Com ing
print(word.upper(), word.lower())    # COMPUTING computing
print(ord("A"), chr(66))             # 65 B
substring counts, a slice stops

The exam's substring(2, 3) means start at position 2 and take three characters. A Python slice [2:5] means start at 2 and stop before 5. Same three letters, two different ways of saying it.

Putting ord, chr and MOD together gives the classic Caesar shift, where % 26 is what makes Y wrap round to B:

Python
def shift_letter(letter, shift):
    position = ord(letter) - ord("A")
    new_position = (position + shift) % 26
    return chr(new_position + ord("A"))

print(shift_letter("C", 3), shift_letter("Y", 3))     # F B
The data types, and changing one into anotherThe five basic data types, one card each. An integer is a whole number such as 42, written int in Python. A real number has a decimal point such as 3.14, written float. A Boolean has only two values, True and False, shown as a switch that is on and a switch that is off. A character is a single symbol such as the letter A, and a string is text inside quote marks. A phone number is stored as a string, because you never do arithmetic on it and because storing it as a number would drop the leading zero, turning 07700 into 7700. Casting changes a value from one type to another: int of the text 42 gives the number 42, str of the number 42 gives the text 42, and int of 3.9 gives 3 because the decimal part is cut off rather than rounded.Integer42-7 0 2025whole numbersintReal3.140.5 -2.75with a decimal pointfloatBooleanTrue Falseonly two valuesboolCharacterAz 7 ?one single symbolstrString"Hi""07700 900123"text in quotesstr1A phone number is a string07700900123you never add phone numbersa number would lose the 007700 as a number = 7700so it is stored as text2Casting: changing type"42"int()42to a whole number42str()"42"to text3.9int()3cuts off the .93
  1. Five data types: integer, real, Boolean, character and string.
  2. A phone number is a string: you never add them, and a number would lose the leading 0.
  3. Casting changes a value from one type to another: int(), str(), float().
Choose the type from what you will do with the value, not from how it looks.
Arithmetic and comparison operatorsThe arithmetic operators as seven cards: plus, minus, multiply, divide, DIV, MOD and power, each with a worked example. Seven divided by two is 3.5. DIV gives the whole number of times it goes in, so 7 DIV 2 is 3, written with a double slash in Python, and MOD gives what is left over, so 7 MOD 2 is 1, written with a percent sign. A picture shows it as seven cookies shared between two people: three each, and one left over. Below, the comparison operators give True or False: 5 equals 5 is True, 5 is not equal to 5 is False, 5 greater than or equal to 6 is False and 5 less than 6 is True. A warning shows the commonest slip: a single equals sign stores a value, while a double equals sign asks whether two values are equal.+add7 + 2= 9-subtract7 - 2= 5*multiply7 * 2= 14/divide7 / 2= 3.5//DIV7 // 2= 3%MOD7 % 2= 1**power2 ** 3= 81DIV and MOD: 7 cookies, 2 people3 each3 each1 left over7 // 2 = 3 (DIV)7 % 2 = 1 (MOD)2Comparing: True or False5 == 5True5 != 5False5 >= 6False5 < 6True= stores a value== asks "are they equal?"34
  1. Arithmetic: + - * / then DIV, MOD and power.
  2. DIV is how many whole times it goes in. MOD is what is left over.
  3. Comparisons ask a question, and the answer is always True or False.
  4. = stores a value. == asks whether two values are equal.
MOD is the clock operator: it is what is left when you have gone round as many times as you can.

Translating whole algorithms

The exam gives you pseudocode to read, to trace, to correct or to complete, and asks you to write your own. In a written paper, an answer in Python is accepted if the logic is unambiguous. In Edexcel Paper 2 the code has to run.

1. A count loop with a running total

OCR reference language
total = 0
for i = 1 to 5
    mark = input("Enter mark")
    total = total + int(mark)
next i
average = total / 5
print("Average: " + str(average))

The program below is the same algorithm. A list stands in for the keyboard so that it gives the same output every time you run it.

Python
marks = [60, 72, 85, 41, 90]
total = 0
for i in range(1, 6):
    mark = marks[i - 1]
    total = total + mark
average = total / 5
print("Average: " + str(average))     # Average: 69.6

2. Selection with a compound condition

OCR reference language
if mark >= 80 AND attendance >= 90 then
    print("Distinction")
elseif mark >= 50 then
    print("Pass")
else
    print("Fail")
endif
Python
def result(mark, attendance):
    if mark >= 80 and attendance >= 90:
        return "Distinction"
    elif mark >= 50:
        return "Pass"
    else:
        return "Fail"

print(result(85, 95), result(85, 70), result(30, 100))     # Distinction Pass Fail

The second call shows why the order matters. A mark of 85 with 70 per cent attendance fails the first test, so it falls through to the second and earns a Pass.

3. A loop that tests first

OCR reference language
secret = 7
guess = 0
tries = 0
while guess != secret
    guess = int(input("Guess"))
    tries = tries + 1
endwhile
print("Found in " + str(tries))
Python
feed = iter([3, 9, 7])
secret = 7
guess = 0
tries = 0
while guess != secret:
    guess = next(feed)
    tries = tries + 1
print("Found in " + str(tries))     # Found in 3

guess is set to 0 before the loop so that the first test has something to compare. A test-first loop needs its variable to exist, and to start at a value that lets the loop begin.

4. Random numbers

The exam's random(1, 6) includes both ends. So does Python's randint, which is unusual, because range does not.

Python
import random
roll = random.randint(1, 6)
print(1 <= roll <= 6)     # True, whichever number came up

The translation checklist

  1. Loops. Add one to the stop value of a count loop. Turn until into if ... break.
  2. Operators. DIV is //, MOD is %, ^ is **.
  3. Text. substring(start, length) is [start:start + length]. ASC is ord and CHR is chr.
  4. Types. input gives a string. Cast it before comparing or calculating.
  5. Equality. = assigns and == compares, in both the exam and Python.
Do not use shortcuts that hide the algorithm

If the question asks you to total a list, write the loop. sum(marks) is perfectly good Python, but the mark scheme is looking for an accumulator that starts at 0 and gains each value. The same goes for max, min and sorted on a question about finding or sorting.

One algorithm as a flowchart, as Python and as pseudocode, with matching steps in matching coloursThe same algorithm written three ways. The flowchart starts, inputs an age, then reaches a decision diamond that asks whether age is greater than or equal to 18. If yes it outputs Adult, if no it outputs Child, and both paths join and reach the end. The Python code has the same steps: age equals int of input, if age is at least 18 print Adult, else print Child. The pseudocode is the same again, ending with endif. The input is coloured blue, the decision yellow, and the two outputs green and red in all three versions, so each step can be matched across them. Rounded ovals mean start and end, slanted boxes mean input and output, and a diamond means a decision.The flowchart1Startinput ageage >= 18 ?yesnooutput "Adult"output "Child"Endage.pyage = int(input("Age? "))if age >= 18:    print("Adult")else:    print("Child")2the same, in pseudocodeage = input("Age? ")if age >= 18 then    print("Adult")else    print("Child")endif3input, outputdecisionstart, endsame colour = same step, in all three
  1. The flowchart: ovals for start and end, slanted boxes for input and output, a diamond for a decision with a yes branch and a no branch.
  2. The Python version has the same steps, matched by colour.
  3. The pseudocode is the same algorithm again. Only the notation changes.
A flowchart, pseudocode and a program are three ways to write one algorithm. Practise moving between them.

Key terms you must be able to define

Pseudocode
A way of writing an algorithm in structured, language-neutral English so it can be read without knowing a programming language.
Casting
Converting a value from one data type to another, such as int("7") or str(7).
MOD
The remainder after whole number division. 17 MOD 5 is 2. Written % in Python.
DIV
Whole number division, discarding the remainder. 17 DIV 5 is 3. Written // in Python.
Count-controlled loop
A loop that repeats a set number of times, such as for i = 1 to 5.
Condition-controlled loop
A loop that repeats until or while a condition is met, such as while or do...until.
Concatenation
Joining two strings end to end, using + in the exam and in Python.
Substring
A part of a string, taken by position and length.
ASCII code
The number that stands for a character. ord gives it and chr turns it back into a character.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefinePseudocode
AnswerA way of writing an algorithm in structured, language-neutral English so it can be read without knowing a programming language.
DefineCasting
AnswerConverting a value from one data type to another, such as int("7") or str(7).
DefineMOD
AnswerThe remainder after whole number division. 17 MOD 5 is 2. Written % in Python.
DefineDIV
AnswerWhole number division, discarding the remainder. 17 DIV 5 is 3. Written // in Python.
DefineCount-controlled loop
AnswerA loop that repeats a set number of times, such as for i = 1 to 5.
DefineCondition-controlled loop
AnswerA loop that repeats until or while a condition is met, such as while or do...until.
DefineConcatenation
AnswerJoining two strings end to end, using + in the exam and in Python.
DefineSubstring
AnswerA part of a string, taken by position and length.

Reach the top grade on this topic

Full marks on translation questions come from checking the five places where the notations disagree.

  • Add one to the stop value of every count loop, and say why in a comment
  • Turn do...until into while True with a break on the exit condition
  • Know that MOD is the remainder, DIV drops it, and ^ is not power in Python
  • Cast the result of input before comparing or calculating with it
  • Write the loop for a total or a count rather than reaching for sum or len

Mistakes that cost marks here

Avoid these
  • Writing range(1, 5) for for i = 1 to 5, so the loop stops one short.
  • Using ^ for a power in Python, which is XOR and gives a strange small number.
  • Comparing input directly with a number without casting, which is a TypeError.
  • Swapping the start and the length in substring(start, length).
  • Writing = when comparing, so the condition assigns instead of testing.
Fun fact

Python went thirty years without anything like a switch statement. match only arrived in Python 3.10, in 2021, and there is still no do...until loop, which is why exam answers use while True and break.

Knowledge check

0 of 10 answered
1Which Python expression is the same as 17 MOD 5 in exam pseudocode?
2What is the value of 17 // 5 in Python?
3Which line is the Python for the exam loop for i = 1 to 5?
4What does 2 ^ 3 evaluate to in Python?
5Which structure replaces an exam do ... until x > 10 loop in Python?
6Which function turns the character "A" into its ASCII code 65?
7What is bool("False") in Python?
8If word = "Computing", what is word[2:5]?
9How does Python store a single character such as "A"?
10What are the values of 7 // 2 and 7 / 2?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

15 marks
1A program contains the lines minutes = total_seconds DIV 60 and seconds = total_seconds MOD 60. State the value of minutes and the value of seconds when total_seconds is 185.2 marks
State

Mark scheme0 / 2
  • Lminutes is 3
  • Lseconds is 5
Model answer

185 DIV 60 is 3, because 60 goes into 185 three times. 185 MOD 60 is 5, because three lots of 60 make 180 and the remainder is 5. So minutes is 3 and seconds is 5.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Write the Python equivalent of the following OCR reference language.3 marks
Write
OCR reference language
total = 0
for i = 1 to 10
    total = total + i * i
next i
print(total)

Mark scheme0 / 3
  • LUses range(1, 11) so that 10 is included
  • LAdds i * i to the total inside the loop
  • LPrints the total after the loop, not inside it
Model answer

The Python loop must run to 10 inclusive, so the stop value is 11.

Python
total = 0
for i in range(1, 11):
    total = total + i * i
print(total)

The print is not indented, so it happens once after the loop has finished. The program prints 385.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3A student writes age = input("Age: ") followed by if age >= 18:. Explain why this raises an error and show how to correct it.4 marks
Explain

Mark scheme0 / 4
  • Linput always returns a string
  • LA string cannot be compared with an integer using >=
  • LThe value must be cast to an integer
  • LCorrected code is age = int(input("Age: "))
Model answer

The input function always returns a string, even when the user types digits. Python cannot compare a string with the integer 18 using >=, so it raises a TypeError. The string has to be converted to an integer first, by casting it.

Python
age = int(input("Age: "))
if age >= 18:
    print("Adult")
The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A Caesar cipher shifts every letter along the alphabet and wraps round after Z. Describe how the MOD operator is used to make the shifted letter wrap round.3 marks
Describe

Mark scheme0 / 3
  • LEach letter is converted to a position from 0 to 25
  • LThe shift is added and the total is MOD 26
  • LThe remainder is always between 0 and 25 so Y plus 3 wraps to B
Model answer

Each letter is first turned into its position in the alphabet, from 0 for A to 25 for Z. The shift is added, then the total is taken MOD 26. The remainder after dividing by 26 can only be between 0 and 25, so a total that goes past 25 comes back round to the start of the alphabet. For example Y is position 24, 24 plus 3 is 27, and 27 MOD 26 is 1, which is B.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Convert the following loop into Python. The loop must behave exactly as the original does.3 marks
Convert
OCR reference language
do
    guess = int(input("Guess: "))
until guess == 7

Mark scheme0 / 3
  • LUses a loop that cannot end by itself such as while True
  • LReads the guess inside the loop and casts it to an integer
  • LUses an if with break when the guess equals 7
Model answer

The body must run once before the test, so the loop is a while True with the exit condition checked at the bottom.

Python
while True:
    guess = int(input("Guess: "))
    if guess == 7:
        break
The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 15