Debugging Basics: How to Find Bugs Systematically
A seller writes to support: their new shop's dashboard crashes every time they open it. You change a line that looks odd, redeploy, and it still crashes. Guessing is slow, and it can add new bugs. This lesson covers debugging basics: a method for finding a bug's real cause, fixing it and keeping it fixed.
Reproduce the bug first
Debugging is finding and fixing the cause of a bug, the gap between what code does and what was meant. The symptom is what someone sees, such as a crash or a wrong total; the cause is the mistake in the code. This loop leads from one to the other:
To reproduce a bug is to make it happen on demand. Start here: if a bug appears only sometimes, a quiet hour after your change may mean it is fixed, or only that the trigger did not happen. Collect the input, steps, app version and where it ran, from the reporter and the logs, the records a program writes as it runs.
Then shrink it to a minimal reproduction: the smallest input and code that still show the bug, quick to rerun. Here, every report comes from a new seller with no orders yet, and the dashboard averages a seller's order totals. Given an empty list, that function crashes every time, so this file, shop.py, is the whole reproduction:
def average_order(totals):
return sum(totals) / len(totals)
print(average_order([]))
Read the error from the bottom up
When Python meets a problem it cannot handle, such as dividing by zero, it raises an exception, an error that interrupts the program. If no code handles it, the program stops and prints a traceback, Python's name for a stack trace: the list of function calls in progress when the error happened, each with its file, line number and function.
Python lists the oldest call first and the newest last, as its heading "most recent call last" says, so start at the bottom. The last line gives the error type and a message: the actual error. Each entry above it is a frame, one call in the chain, and the frame just above the error is where it happened. Running shop.py prints:
In order: the last line is what went wrong; line 2, inside average_order, is where; line 4, at the file's top level, which Python calls <module>, made the call. From Python 3.11, the ^ and ~ marks underline the failing part of each line.
The named line is where Python noticed the problem, not always where the mistake is. Here the two match: average_order never decides what the average of no orders should be. But if a seller with orders got an empty list, the mistake would be further up, in the code that loaded them. Languages differ, too: a Java stack trace puts the error first and the newest call at the top.
Narrow it down: prints, a debugger and bisecting
Often the error does not point at the cause, or there is none, only a wrong number. Then find the last point where values are right and the first where they are wrong: the mistake lies between.
Print the values
Add a temporary print("totals =", totals) as the first line inside average_order and run the file in a terminal: totals = [] appears above the traceback, confirming that the list arrives empty. Delete such prints afterwards, so they do not end up in a commit.
Use a debugger
A debugger is a tool that pauses a running program so you can look inside it. You set a breakpoint, a line to pause at, then inspect variables and run one line at a time; in VS Code, click the editor margin beside a line. Python's built-in debugger is pdb: put breakpoint() on its own line above the return and run the file. Python 3.12 pauses there, and you type p totals at the (Pdb) prompt:
> /app/shop.py(3)average_order()
-> return sum(totals) / len(totals)
(Pdb) p totals
[]
The first line shows where it paused (file, line 3, function), and the arrow marks the next line to run. p prints a value, n runs one line, s steps into a call, and c continues, here into the same crash.
Bisect
To bisect is to halve the search with each check. Say a value is right at the start of a long function and wrong at the end. Check it half-way: if it is still right, the mistake is in the second half; if not, it is in the first. Then check the middle of what is left, and repeat:
You can also bisect by switching code off: when parts run independently, disable half, and if the bug survives, it is in the half still running. For a bug that appeared recently, git bisect halves your history of commits: you mark one good and one bad, and Git picks commits in between to test.
One hypothesis, one change at a time
A hypothesis is a specific guess about the cause that a test can prove wrong. "The dashboard is broken" is not one; "average_order gets an empty list for new sellers" is, and one print checks it. Test one at a time, so each result means something definite.
Change one thing at a time, too. If you edit three lines and the bug vanishes, you do not know which edit fixed it, or whether the others broke something. Undo a change that did not help before you try the next.
Write down what you tried and what happened, in the ticket or a notes file, so you never repeat a test and a teammate can start from your evidence.
After the fix: lock it in
Fix the cause, not the symptom: hiding every error on the dashboard would stop this crash and hide the next bug too. Here the team decides that no orders means an average of ₹0, so average_order returns 0 for an empty list. Then rerun the reproduction to confirm the cure.
Next, add a regression test: one that fails without the fix and passes with it, so the bug cannot quietly return. A regression, as Software Testing Basics explained, is something that broke after a change. This pytest unit test, the kind from the last lesson, does it:
def test_average_order_of_no_orders_is_zero():
assert average_order([]) == 0
Run it before the fix and watch it fail with the same ZeroDivisionError: a test you have never seen fail may not test what you think. Last, look for the same mistake elsewhere: search for other divisions by a count with your editor or git grep, Git's search across tracked files.
Check yourself
A user says checkout "sometimes" fails. You change a line, try once, and it works. Why is the bug not proved fixed?
You never reproduced it, so one success may only mean the trigger did not happen. Find the conditions that make it fail every time, then show the fix stops it.
A traceback ends with KeyError: 'email'. Where do you start, and must the fix go on the last frame's line?
Start with the last line: a dictionary had no 'email' key. Not necessarily: it may have been built without the key earlier, so follow the frames upwards.
You changed three things at once and the bug went away. What do you not know, and what next?
Which change fixed it, and whether the others broke something. Undo them, reapply one at a time against the reproduction, and add a regression test.