Python Debugging in Practice
Debugging is finding the wrong line by testing small parts. Prints find it first, and a breakpoint proves it.
A wrong total
The total of 10, 20 and 30 must be 60. The program prints 30 instead.
def total(nums):
result = 0
for n in nums:
result = n
return result
print(total([10, 20, 30]))Prints show the wrong step
Each print shows the running total. The value is replaced, not added.
def total(nums):
result = 0
for n in nums:
result = n
print("now:", result)
return result
print("Total:", total([10, 20, 30]))The fix
The line now adds each number. The total prints 60.
def total(nums):
result = 0
for n in nums:
result = result + n
return result
print("Total:", total([10, 20, 30]))One breakpoint to prove it
The file holds the fixed program plus one breakpoint() line. After two steps, result holds 10.
$ python3 total.py
> total.py(4)total()
-> for n in nums:
(Pdb) n
> total.py(5)total()
-> result = result + n
(Pdb) n
> total.py(4)total()
-> for n in nums:
(Pdb) p result
10
(Pdb) c
Total: 60Example
def average(nums):
total = 0
for n in nums:
total = total + n
print("running total:", total)
return total / len(nums)
print("Average:", average([10, 20, 30]))Key points
- Debugging: finding the wrong line by testing small parts
- Use prints to show values while the program runs
- A print that shows the wrong value narrows the search
- Use breakpoint() once prints point at one line
- Fix one line, then run the program again
In this example, average adds three scores. The prints show the running total at each step. The totals 10, 30 and 60 grow as they must. The average prints 20.0, so the sum was right.
Note
Remove the prints and the breakpoint before you finish.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Prints show now: 10, now: 20, now: 30. What does that tell you?