Reading code, errors and testing
How to predict the exact output of a program, the error types you must recognise, tracing tables, testing with expected values, and a free Python playground.
Based on: exercise sessions (exam level exercises, test files of the assignment) and the Python part of the exam · About 60 minutes
Predicting output, step by stepImportant
A large share of the practical exam asks what a program prints, exactly, or whether it stops with an error. Guessing does not work; tracing does. Work as the interpreter works: one line at a time, keeping a table of every variable.
- Write every variable as a column; add a row each time a value changes.
- For a loop, note the condition at the start of every round; stop the moment it is False.
- For a function call, start a fresh mini table for the parameters and local variables; cross it out at return.
- Write output exactly: commas in print give one space,
end=""keeps the line open, floats show.0, strings appear without quotes and lists with quotes. - Before each line, ask whether it can fail: a missing key, an index past the end, a name that only exists inside a function, a method a type does not have.
Trace a while loop
r = 31; R = 6; while r > R: r -= R; R += 4; then print(r - R).
Round 1
Round 2
Round 3
Check
The program prints 1 - 18 = -17. This is exercise p14 of the predict lab.
Error types to recogniseImportant
| Error | Typical cause | Example |
|---|---|---|
| SyntaxError | the code is not valid Python: missing colon, unclosed bracket or quote | if x > 3 print(x) |
| IndentationError | a block is not indented correctly | a body line with no indentation after def |
| NameError | a name that does not exist (typo, local variable used outside, missing quotes) | print(num) after a function, d[john] |
| TypeError | an operation on the wrong type, or a wrong number of arguments | "5" + 3, t[0] = 9 on a tuple |
| ValueError | right type, impossible value | int("abc"), lst.remove(99) |
| IndexError | a position past the end of a sequence | [1, 2][2] |
| KeyError | a dictionary key that does not exist | d["dave"] |
| AttributeError | a method the type does not have | (1, 2).append(3) |
| ZeroDivisionError | dividing by zero | 5 / 0, 5 % 0 |
A SyntaxError is found before anything runs, so the program prints nothing at all. Every other error is raised when the line is reached: everything printed before that line is still shown, then the error stops the program. That is the interpreter at work.
Testing your own codeImportant
Step 6 of programming is testing: the program must not only run, it must give logically correct results. The assignment of the course comes with a test file that calls each function with known inputs and compares the result with the expected value. Do the same yourself:
def is_palindrome(word):
w = word.lower()
return w == w[::-1]
print(is_palindrome("Level") == True)
print(is_palindrome("Python") == False)
print(is_palindrome("") == True) # edge case- Test a normal case, every branch of an if, and edge cases: zero, an empty list or string, one element, the first and last value of a range.
- Compare with a result you computed another way (by hand, in a spreadsheet).
- When a test fails, add temporary
printstatements to see the values, then remove them again. The assignment rules ask for clean functions without print statements.
The practical half of the examNeutral
Python counts for half of the written exam. Expect questions that ask you to predict output, find and correct errors, complete or write short programs and functions in the style of the exercise sessions, and translate an algorithm into Python. There is no computer at the exam: practise writing code on paper, with correct indentation, and check it afterwards in the playground.
Read the exam guide for the rules on the minimum score per part. The optional take-home assignment of 2024-2025 could add a bonus point on the Python part when all private tests passed.
Key takeaways
- Trace with a table: one column per variable, one row per change.
- Output must be exact: spaces from commas, .0 on floats, None from functions without return.
- SyntaxError stops everything before it starts; other errors stop at the failing line.
- Know the nine error types and a typical cause for each.
- Test normal cases, every branch and edge cases against expected values.
All cards known
Reset the progress or pick another unit to keep practising.
Multiple choice (8)
d = {"john": 40}; print(d[john]). What happens?
print("start"); x = [1, 2][5]; print("end"). What is shown?
Which error does int("12a") raise?
What does print(3 * "ab", 3 * 2.0) show?
for i in [2, 3]: print(i * (i * 2 + 1)). What is printed?
Which situation raises an AttributeError?
def f(): return 1; print(2). What does print(f()) show?
Which is an edge case for a function that averages a list?
Exam-style open questions (2)
Predict and explain
Predict the output of: lst = [1, 5, 3]; i = 1; result = 0; while lst: result += lst.pop() * i; i += 1; print(result). Show your tracing table.
Show a model answer outline
- pop takes from the end: 3, then 5, then 1.
- result = 3 x 1 = 3; then 3 + 5 x 2 = 13; then 13 + 1 x 3 = 16.
- The empty list is False: the loop stops.
- Output 16.
Find the errors
A student writes: def average(lst) / total = 0 / for x in lst: total += x / return total / len(lst), then calls print(average([])). Name the syntax problem and the runtime problem, and fix both.
Show a model answer outline
- Missing colon after def average(lst).
- With an empty list, len is 0: ZeroDivisionError.
- Fix: add the colon and return 0 (or None) when the list is empty.
LabPredict the output
Write your prediction first, then run the program. For a program that stops with an error, type the output before the error and the error name on the last line.
LabPython playground
Use it to check code you wrote on paper. The sandbox has no internet, no access to this page and a limit of 4 seconds and 20,000 characters of output.