Debugging
Python · Unit 20: Testing and debugging
- Full plan
- Python
- 8 exercises
When the result is not the one you expected, do not stare at the code: print.
A print inside the loop shows you the variable round by round, and that is where what you cannot read jumps out.
total = 0
for n in [5, 3, 2]:
total = n
print("n:", n, "total:", total)
print("Total:", total)Prints
n: 5 total: 5 n: 3 total: 3 n: 2 total: 2 Total: 2
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Complete the tracing print so it shows what the function computed.
3. Multiple choice
Your program crashes with
ZeroDivisionError (line 2): division by zero, and line 2 isreturn sum(ns) / len(ns). Where do you start looking?4. Find the bug
This program should add up the prices, and the
prints are there to follow it. Which line has the error?5. Find the bug
The tracing print should show the total, but the program crashes. Which line has the error?
6. Predict the output
What does this code print?
7. Put the lines in order
Put the function in order with its tracing print inside the loop.
8. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.