Debuggers and Breakpoints
Level 2 · Checking and fixing code
How a debugger pauses your program on a breakpoint so you can look inside. When a print line or a rubber duck finds the bug faster.
Course contentsLesson 5 of 13
Level 1 · The editor
Level 2 · Checking and fixing code
Level 3 · Trying code out
Level 4 · Other people's code
Level 5 · Building the project
After this lesson you can
- Set a breakpoint and step through code
- Find a bug with print lines
- Explain code out loud to find a slip
12 mincovers 4 glossary entries
Worth reading first: Linters and Formatters
How to stop a program and look inside
A debugger runs your program one step at a time. You mark a line with a breakpoint, and the program pauses just before that line runs. Then you can see the value of every name and step forward line by line. Python has had a built-in breakpoint() call since version 3.7, in 2018.
Most editors let you set a breakpoint by clicking beside the line number. A red dot appears. Run the program in debug mode, and it stops on the dot. A panel shows each value, and buttons step to the next line, step into a function, or carry on to the next breakpoint.
The point is to watch the values change. A bug is a place where a value is not what you thought. Stepping through shows you the exact line where a total turns into zero, or where a list loses an item.
Print debugging is the older way, and it still works well. You add lines that print values as the code runs. Run it, and read the output. The first value that looks wrong points at the bug. When it is fixed, you take the print lines out again.
Print lines are quick to add and work anywhere, even on a server with no editor. A debugger shows each value at once and leaves the code alone. Many people start with a print line. They reach for the debugger when the bug hides well.
Rubber duck debugging needs no tool at all. You explain your code out loud, line by line, to something that cannot answer, like a toy duck on the desk. To say what a line does, you have to read what it really does, not what you hoped. The gap between the two is often the bug.
Two mistakes are common. Leaving a breakpoint() call in code that goes live freezes the real app, waiting for a debugger. Leaving print lines in clutters the output and can leak private data into logs. Search for both before you commit.
price = read_price()
print("DEBUG price:", price)
breakpoint() # the program pauses here
total = price * qtyWorked example
Jack's basket total is short
Jack's shop adds up 5 items in a basket, but the total always leaves one out. He reads the loop out loud to his desk duck, one line at a time.
At the third line he says it stops before the last item, and hears the bug. He changes one number, and the total is right.
The words for this lesson4
Check yourself
What does a breakpoint do?
Finished this lesson?
Marking it complete also marks its 4 glossary entries learned, which updates your roadmap and your saved page. 0 are already marked.