Errors & testing
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Three kinds of error
- A syntax error breaks the rules of Python, so the code will not run.
- A runtime error crashes the program while it is running.
- A logic error runs fine but gives the wrong answer.
Syntax errors
- These are typos: a missing
:, an unclosed quote, a wrong indent. - Python refuses to start and shows you the line.
- Fix the spelling or punctuation, then run again.
Runtime errors
- The code starts, then hits something it cannot do.
- Examples:
10 / 0, orint("hello"), or reading past the end of a list. - The program stops at that line with a message.
Logic errors
- The program runs to the end but the result is wrong.
- Example: using
-where you meant+, or stopping a loop too early. - These are the hardest to find — the computer did exactly what you wrote.
Read the traceback
- When a program crashes, Python prints a traceback.
- Read the last line first: it names the error and what went wrong.
- The line number tells you where to look.
Traceback (most recent call last):
File "<program>", line 2, in <module>
print(10 / 0)
ZeroDivisionError: division by zero
Test with chosen data
- Do not trust code until you have tested it.
- Use normal data, boundary data (like
0), and extreme data. - Check each answer against what you worked out by hand.
def square(n):
return n * n
print(square(3)) # normal -> 9
print(square(0)) # boundary -> 0
print(square(-2)) # negative -> 4
Now you try
- Each task has a logic error to fix, or a crash to prevent.
- Press Check answer to test your fix against several cases.
This function should add a and b, but it has a logic error — it subtracts. Fix it so it returns the sum.
Click Run to see the output here.
sum_to(n) should return 1 + 2 + ... + n, but it stops one number too early (an off-by-one logic error). Fix the range so it includes n.
Click Run to see the output here.
Write safe_divide(a, b) that returns a / b, but prevents a runtime crash: if b is 0, return 0 instead.
Click Run to see the output here.