22 min read
Debugging Your Programs
Read error messages, fix syntax and runtime errors, and track down logic errors with print statements and trace tables.
Reading an Error Message
Press Run and read the errorPython
prices = [280, 450, 120]total = 0for p in prices: total += paverage = total / len(price)print(average)Read a Python error from the bottom up:
- The last line names the error and explains it: NameError: name 'price' is not defined.
- The line above shows the line number and the code where it happened.
- Here the variable is prices, not price. Fix the name and run again.
Common Errors and Fixes
| Errors you will meet | ||
|---|---|---|
Finding Logic Errors
No error message — but is it right?Python
# Should output the average of three marks (60, 70, 80 -> 70)mark1 = 60mark2 = 70mark3 = 80average = mark1 + mark2 + mark3 / 3print("Average:", average)Expected output
Average: 156.66666666666666
The program runs, but 156.67 is clearly wrong. Ways to find the problem:
- Predict the right answer first (70), then compare.
- Add print() statements to show values at each stage, e.g.
print("total:", mark1 + mark2 + mark3). - Trace the calculation by hand with a trace table.
- Check precedence: only mark3 was divided by 3. The fix is
(mark1 + mark2 + mark3) / 3.
FixedPython
mark1 = 60mark2 = 70mark3 = 80average = (mark1 + mark2 + mark3) / 3print("Average:", average)Expected output
Average: 70.0
Practice
Which of these are LOGIC errors (the program runs but gives wrong results)?
Choose all that apply.
More lessons in Python Programming · Next: Python Worksheet · Previous: Putting It Together: the Shop Till
