🎓 A1Learner
🔍
0 of 52 lessons completed

Python Debugging With pdb

pdb is the debugger that comes with Python. breakpoint() pauses the program inside pdb.

Pause and print a value

The file holds the closing program plus one breakpoint() line. pdb pauses at the loop, and p prints result.

$ python3 total.py
> total.py(4)total()
-> for n in nums:
(Pdb) p result
0
(Pdb) c
Total: 30

Step through the loop

n runs one line at a time. 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: 30

Quit from inside pdb

q quits the debugger and stops the program.

$ python3 total.py
> total.py(4)total()
-> for n in nums:
(Pdb) q

Example

def total(nums):
    result = 0
    for n in nums:
        result = result + n
    return result

print("Total:", total([10, 20]))

Key points

  • Debugger: a tool that pauses a program so you can look inside it
  • Use breakpoint() to pause the program at one line
  • Use n to run the next line
  • Use p followed by a name to print its value
  • Use c to carry on running
  • Use q to quit the debugger

In this example, total adds 10 and 20. The loop runs twice. result grows from 0 to 10, then to 30. The print shows Total: 30. The transcripts above pause this same program.

Note

pdb waits for typed commands, so it needs a live terminal.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

You pause in pdb and want the value of result. What do you type?