hanegreefs.com/Business Information SystemsBIS
Python 5 · unit 8 of 16

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.

  1. Write every variable as a column; add a row each time a value changes.
  2. For a loop, note the condition at the start of every round; stop the moment it is False.
  3. For a function call, start a fresh mini table for the parameters and local variables; cross it out at return.
  4. 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.
  5. 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.
Worked example

Trace a while loop

r = 31; R = 6; while r > R: r -= R; R += 4; then print(r - R).

1

Round 1

31 > 6: r = 25, R = 10
2

Round 2

25 > 10: r = 15, R = 14
3

Round 3

15 > 14: r = 1, R = 18
4

Check

1 > 18 is False: leave the loop
Answer

The program prints 1 - 18 = -17. This is exercise p14 of the predict lab.

Error types to recogniseImportant

ErrorTypical causeExample
SyntaxErrorthe code is not valid Python: missing colon, unclosed bracket or quoteif x > 3 print(x)
IndentationErrora block is not indented correctlya body line with no indentation after def
NameErrora name that does not exist (typo, local variable used outside, missing quotes)print(num) after a function, d[john]
TypeErroran operation on the wrong type, or a wrong number of arguments"5" + 3, t[0] = 9 on a tuple
ValueErrorright type, impossible valueint("abc"), lst.remove(99)
IndexErrora position past the end of a sequence[1, 2][2]
KeyErrora dictionary key that does not existd["dave"]
AttributeErrora method the type does not have(1, 2).append(3)
ZeroDivisionErrordividing by zero5 / 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.

Common trapA program can also do something worse than crash: run forever. If no statement in a loop body changes the condition, the honest answer to "what does it print" is "an infinite loop", possibly with output repeated without end.

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 print statements 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.

Loading cards
Question
Click, tap or press space to flip
Answer

Multiple choice (8)

Question 1 · Python 5

d = {"john": 40}; print(d[john]). What happens?

Why: Without quotes Python looks for a variable called john.
Question 2 · Python 5

print("start"); x = [1, 2][5]; print("end"). What is shown?

Why: The error stops the program at line 2, after the first print.
Question 3 · Python 5

Which error does int("12a") raise?

Why: The type is right (a string) but the content cannot be converted.
Question 4 · Python 5

What does print(3 * "ab", 3 * 2.0) show?

Why: Repetition of a string, and a float product.
Question 5 · Python 5

for i in [2, 3]: print(i * (i * 2 + 1)). What is printed?

Why: 2 x 5 = 10 and 3 x 7 = 21.
Question 6 · Python 5

Which situation raises an AttributeError?

Why: Tuples have no append method.
Question 7 · Python 5

def f(): return 1; print(2). What does print(f()) show?

Why: return ends the function before the print.
Question 8 · Python 5

Which is an edge case for a function that averages a list?

Why: An empty list gives a division by zero unless handled.

Exam-style open questions (2)

Open question · Python 5

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.
Open question · Python 5

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.