Debugging
Debugging means finding why a program does the wrong thing, fixing the cause, and checking the fix.
Use a repeatable process
- Decide what the program should print for a small example.
- Run it and note what it actually prints.
- Read any error message: its type and its line number.
- Find the first line where a value goes wrong.
- Change one thing at a time.
- Run the example again, then try other inputs.
Recognise the kind of problem
- Syntax error: Python cannot read the code, so nothing runs. A missing
colon after
deforifis common. - Runtime error: the code starts but stops on one line.
- Logic error: the code runs but gives the wrong answer.
This program has a runtime error:
print("start")
print("4" + 1)
start prints, then Python stops with this message:
TypeError: can only concatenate str (not "int") to str
The message names the line and says text and a number cannot be added.
int("4") + 1 fixes it.
Find a logic error
This line should print the average of 3 and 5, which is 4:
print(3 + 5 / 2)It prints 5.5. Division happens before addition, so only 5 is halved.
Brackets fix the cause:
print((3 + 5) / 2)Now it prints 4.0.
Inspect a value without changing the calculation
This loop should total the scores, but it prints 2, not 10. A temporary
print() inside the loop shows each step:
total = 0for score in [3, 5, 2]: total = score print("score:", score, "total:", total)print(total)total never grows: it is replaced by each score. The fix is
total = total + score. Remove temporary prints when the bug is fixed.
Note: a return inside a loop ends the function as soon as that return
executes. If it is inside an if, that may happen on a later pass or not at all. See
Stopping a Search with return.
See also: Tracing Code, The range() Function, Parameters & Return.
Your turn
sum_up_to(limit) should add the numbers from 1 up to and including
limit. Fix the bug so both calls print the right total.
6 1
def sum_up_to(limit): total = 0 # fix the range so it includes limit for number in range(1, limit): total = total + number return totalprint(sum_up_to(3))print(sum_up_to(1))Advanced reading
- Reading a traceback — follow an error back through several function calls.
- Checking assumptions with assert — make a program stop as soon as a value is wrong.