KS3 · Python Programming

Python debugging challenge

Free worked examples, independent practice and self-check answers.

Read the error, find the cause

Debugging means systematically locating and correcting defects. Syntax errors prevent parsing; runtime errors arise while a program runs; logic errors produce incorrect results.

scores = [12, 15, 9]
total = 0
for score in scores:
    total = score
mean = total / len(scores)
print(mean)

The program runs but the output is incorrect. Fix the logic error without using sum().

Suggested solution
scores = [12, 15, 9]
total = 0
for score in scores:
    total += score
mean = total / len(scores)
print(mean)  # 12.0

Extension

Adapt the program to deal safely with an empty list.

Debugging as a repeatable process

Reproduce the error, read the message or incorrect output, and isolate the smallest piece of code that demonstrates it. Trace the relevant variables and compare actual behaviour with the expected result. Change one thing, then rerun the original test.

Try our Python tracing and debugging challenges for short exercises with immediate feedback.