Skip to main content
Editor

Exam Pseudocode in Python: Every Construct Side by Side

Beginner35 min2 exercises25 XP
0/2 exercises

The Computer Science Principles exam writes its code questions in its own pseudocode, so the fastest way to read them is to know exactly how each line would look in Python, and where the two languages quietly disagree.

You get the reference sheet in the exam, so you do not have to memorize the notation. What costs points is the handful of places where it behaves differently from Python. Each one is marked below, and you can type any pseudocode from this page into the pseudocode runner to watch it run.

How do assignment and DISPLAY work?

PseudocodePython
a ← 7a = 7
a = b (a comparison)a == b
a ≠ ba != b
DISPLAY(a)print(a, end=" ")
x ← INPUT()x = input()

The arrow ← stores a value. A single = in pseudocode compares, like == in Python. Mixing these up is the most common slip when reading exam code.

DISPLAY shows a value followed by a space, not a new line. Three DISPLAY calls in a row print on one line.

DISPLAY puts values on one line, separated by spaces
def display(value):
print(value, end=" ")
a = 7
b = a
a = a + 3
display(a)
display(b)
display(a == b)
Output
10 7 False

How do the arithmetic operators compare?

PseudocodePythonExample
a + b, a - b, a * bthe same
a / ba / b17 / 5 is 3.4
a MOD ba % b17 MOD 5 is 2
RANDOM(a, b)random.randint(a, b)RANDOM(1, 3) can be 1, 2 or 3

MOD has the same precedence as * and /, the same as % in Python, so 2 + 7 MOD 3 is 2 + 1, which is 3. RANDOM(a, b) includes both ends, and so does Python's random.randint(a, b). (Python's random.randrange(a, b) leaves out b, so do not swap them.)

MOD and RANDOM in Python
import random
print(17 / 5) # 3.4
print(17 % 5) # 2, the remainder
print(2 + 7 % 3) # 3: % happens before +
rolls = [random.randint(1, 3) for _ in range(20)]
print(sorted(set(rolls))) # both ends appear: [1, 2, 3]
Output
3.4
2
3
[1, 2, 3]

How do IF and the loops translate?

PseudocodePython
IF(condition) { ... }if condition:
IF(condition) { ... } ELSE { ... }if condition: ... else: ...
REPEAT n TIMES { ... }for _ in range(n):
REPEAT UNTIL(condition) { ... }while not condition:
FOR EACH item IN aList { ... }for item in a_list:
NOT, AND, ORnot, and, or

The reference sheet has no ELSE IF. A chain of choices is written as an IF nested inside an ELSE, which Python would write with elif.

REPEAT UNTIL stops when its condition becomes true, the opposite of Python's while, which keeps going while its condition is true. The condition is checked before each pass, so the body can run zero times.

REPEAT UNTIL is a while loop with the condition flipped
# REPEAT UNTIL (count = 3) { count ← count + 1 }
count = 0
while not (count == 3):
count += 1
print("count:", count)
# Checked before each pass: if the condition is already true, the body never runs
count = 5
passes = 0
while not (count >= 3):
passes += 1
print("passes:", passes)
Output
count: 3
passes: 0

Why do lists start at 1?

Exam lists number their elements from 1: the first element of aList is aList[1]. Python counts from 0, so the same element is a_list[0]. Any index from the exam becomes one less in Python.

PseudocodePython
aList ← [10, 20, 30]a_list = [10, 20, 30]
aList[1] (the first element)a_list[0]
aList[i] ← xa_list[i - 1] = x
APPEND(aList, x)a_list.append(x)
INSERT(aList, i, x)a_list.insert(i - 1, x)
REMOVE(aList, i)a_list.pop(i - 1)
LENGTH(aList)len(a_list)

Two more differences matter:

  • An index outside the list stops the program in pseudocode. Python allows negative indexes (a_list[-1] is the last element), and insert with a large index quietly appends, but on the exam index 0, a negative index or one past the end is an error.
  • `aList ← bList` makes a copy. In Python, a_list = b_list makes both names refer to the same list, so changing one changes the other. Use b_list.copy() to get the exam's behaviour.
  • Assigning a list: a copy in pseudocode, a shared list in Python
    b_list = [1, 2, 3]
    shared = b_list # Python: both names, one list
    copied = b_list.copy() # what aList ← bList means on the exam
    b_list.append(4)
    print("shared:", shared) # [1, 2, 3, 4]
    print("copied:", copied) # [1, 2, 3]
    Output
    shared: [1, 2, 3, 4]
    copied: [1, 2, 3]
    A list that follows the exam rules
    class ExamList:
    """A list indexed from 1, where a bad index is an error."""
    def __init__(self, items):
    self.items = list(items)
    def _check(self, i):
    if not 1 <= i <= len(self.items):
    raise IndexError(f"index {i} is outside the list of {len(self.items)}")
    def get(self, i):
    self._check(i)
    return self.items[i - 1]
    def insert(self, i, value):
    self._check(i)
    self.items.insert(i - 1, value)
    def remove(self, i):
    self._check(i)
    del self.items[i - 1]
    scores = ExamList([70, 85, 90])
    print(scores.get(1)) # 70, the first element
    scores.insert(2, 80) # shifts 85 and 90 right
    scores.remove(1) # shifts everything left
    print(scores.items) # [80, 85, 90]
    try:
    scores.get(0)
    except IndexError as error:
    print("Error:", error)
    Output
    70
    [80, 85, 90]
    Error: index 0 is outside the list of 3

    How are procedures written?

    PseudocodePython
    PROCEDURE name(a, b) { ... }def name(a, b):
    RETURN(expression)return expression
    result ← name(1, 2)result = name(1, 2)

    Arguments are matched to parameters in order, as in Python. RETURN can appear anywhere inside a procedure and ends it at once.

    A procedure that finds the largest value, both ways
    # PROCEDURE findMax(numbers)
    # {
    # max ← numbers[1]
    # FOR EACH num IN numbers
    # {
    # IF (num > max)
    # {
    # max ← num
    # }
    # }
    # RETURN (max)
    # }
    def find_max(numbers):
    largest = numbers[0] # numbers[1] in pseudocode
    for num in numbers:
    if num > largest:
    largest = num
    return largest
    print(find_max([4, 17, 9, 12]))
    Output
    17

    What about the robot?

    Some questions show a robot in a grid. MOVE_FORWARD() moves it one square in the direction it faces, ROTATE_LEFT() and ROTATE_RIGHT() turn it 90 degrees in place, and CAN_MOVE(direction) is true when the square in that direction (left, right, forward or backward, relative to where it faces) is open. If the robot is told to move into a blocked square or off the grid, it stays put and the program stops. Python has no built-in robot; the grid robot lesson builds one, and the pseudocode runner draws the grid for you.

    Practice

    Translate a procedure
    Write Code

    Translate this pseudocode into a Python function count_above(values, limit):

    PROCEDURE countAbove(values, limit)
    {
       count ← 0
       FOR EACH v IN values
       {
          IF (v > limit)
          {
             count ← count + 1
          }
       }
       RETURN (count)
    }
    def count_above(values, limit):
    # Your code here
    pass
    INSERT with exam rules
    Write Code

    Write exam_insert(a_list, i, value) that behaves like the exam's INSERT(aList, i, value): it puts value at position i, counting from 1, and shifts the later elements right. Return the list.

    If i is not a valid position in the list (less than 1 or more than its length), return the string "error" instead and leave the list unchanged.

    def exam_insert(a_list, i, value):
    # Your code here
    pass

    Check your understanding

    What is displayed?

    aList ← [5, 10, 15, 20]
    DISPLAY (aList[2])
    Answers

    What is displayed?

    x ← 0
    REPEAT UNTIL (x ≥ 10)
    {
    x ← x + 4
    }
    DISPLAY (x)
    Answers

    What is displayed?

    aList ← [1, 2, 3]
    bList ← aList
    APPEND (aList, 4)
    DISPLAY (LENGTH(bList))
    Answers

    What is displayed?

    count ← 7
    REPEAT UNTIL (count > 5)
    {
    count ← count - 1
    }
    DISPLAY (count)
    Answers

    Which two Python lines do the same thing as REMOVE(aList, 1)?

    Select 2 answers.

    Answers

    What is displayed?

    PROCEDURE mystery(n)
    {
    IF (n MOD 2 = 0)
    {
    RETURN (n / 2)
    }
    RETURN (n * 3)
    }
    DISPLAY (mystery(4))
    DISPLAY (mystery(5))
    Answers

    Which Python expression gives every value that RANDOM(1, 6) can?

    Answers

    Exam topics: the exam reference sheet, used across 3.1 Variables and Assignments (AAP-1.B), 3.3 Mathematical Expressions (AAP-2.C), 3.6 to 3.8 Conditionals and Iteration (AAP-2.H, AAP-2.K), 3.10 Lists (AAP-2.N, AAP-2.O), 3.12 Calling Procedures (AAP-3.A) and 3.15 Random Values (AAP-3.E)

    Related Tutorials

    Was this tutorial helpful?