Course contents · Lesson 16 of 17

Debugging Basics: How to Find Bugs Systematically

Testing and Quality · Lesson 16 of 17 · 10 min Engineer

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:

Flowchart of the debugging loop. Reproduce the bug so you can trigger it on demand; if you cannot, collect the inputs, steps and version first. Then read the error, starting at the last line. Then form one hypothesis, a guess you can test, and test it with prints, a debugger or bisecting. A decision asks: confirmed? No leads to write it down, then a new guess. Yes leads to fix the cause and rerun the reproduction, add a regression test that fails without the fix, check for the same bug in other code, and close the bug. A banner says find the cause before you change the code
Every step before the fix gathers evidence: the code changes only after a test confirms the cause.

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:

A terminal running python /app/shop.py prints a traceback. Heading: Traceback, most recent call last. Then File /app/shop.py, line 4, in module, with the code print(average_order([])) underlined. Then File /app/shop.py, line 2, in average_order, with the code return sum(totals) / len(totals) and the division sign marked. The last line is ZeroDivisionError: division by zero. Callouts number the reading order from the bottom: 1, what went wrong, the error type and message; 2, where it broke, line 2 in average_order; 3, who called it, line 4 at the top level. Notes say the newest call is last, and that the ^ and ~ marks underline the failing part in Python 3.11 and later. A banner says the failing line may not hold the mistake
Read a Python traceback upwards: what went wrong, then where, then who called it.

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:

Illustrative example of bisecting a 100-line function in which a value is right at line 1 and wrong after line 100. Check 1, after line 50: still right, so the bug is in lines 51 to 100, 50 left. Check 2, after line 75: wrong, so lines 51 to 75, 25 left. Check 3, after line 63: right, so lines 64 to 75, 12 left. Check 4, after line 69: wrong, so lines 64 to 69, 6 left. Checks 5 to 7, after lines 66, 68 and 67, leave only line 68. A banner says 100 lines need at most 7 checks and 1,000 lines need 10
Each check halves what is left, so doubling the code adds only one more check.

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.