Debugging basics: read the error, isolate the problem, fix it

Debugging is the work of finding why a program does something different from what you expected, and fixing that cause. It is not guessing, and it is not rewriting the whole program in the hope that the bug goes away. A steady method works better than speed: reproduce the bug, read the error, narrow the cause to one place, change that one place, and test again.
Every programmer debugs, including programmers who write a lot of code. A bug is usually a small mismatch between what the code says and what the programmer meant, such as a wrong variable, a missed case, or data in a shape the code did not expect. The method in this guide works in Python, and the same steps work in other languages, because the steps are about evidence, not about one tool.
Reproduce the bug before you fix it
A bug you cannot reproduce is hard to fix, because you cannot tell whether a change helped. Start by running the program with the same input that showed the problem, and write down what it should do and what it actually does. Those two sentences are the test for every fix that follows. If the program should print an average of 10 and it prints 0, that gap is the bug, and any fix must close that gap without breaking other inputs.
Consider a small function that should return the average of a list of numbers. A beginner version might look correct at a glance, but it fails in a way that teaches the whole method.
def average(numbers):
total = 0
for n in numbers:
total = total + n
return total / len(numbers)
print(average([10, 20, 30]))
This version prints 20.0, which is correct for that input, because 60 divided by 3 is 20. Now try it with an empty list, and Python raises a ZeroDivisionError, because dividing by zero is not allowed. That is not a flaw in the idea of an average. It is a missing case: the function was written for a list with numbers in it, and no one told it what to do when the list is empty. Once you see the case, the fix is a decision about behaviour, not a guess about syntax.
Read the error, then isolate the cause
When a program stops with an error, read the last line first. That line names the error and often says what went wrong in plain terms. Then look at the line number in the traceback, and open that line in your file. The error handling guide explains common error names, and the same reading habit applies here: start at the end of the message, not at the top.
Not every bug raises an error. Some bugs produce a wrong answer and keep running, which is harder to spot. For those bugs, print the values that matter at chosen points in the program. Print the input to a function, print the result after a loop, and print the value before a decision is made. Compare each printed value with what you expected, and the first place where they differ is near the cause.
def average(numbers):
total = 0
for n in numbers:
total = total + n
print("total:", total, "count:", len(numbers))
return total / len(numbers)
The print line above is temporary. It is there to show evidence, and it should be removed once the bug is found. A program left full of debug prints is harder to read, and it may print data that should stay private. Treat debug prints as scaffolding: useful while you build, removed when the work is done.
Isolation means narrowing the search. If a program has three steps, test each step on its own with a known input. If the first two steps give the right result and the third does not, the bug lives in the third step, and you can stop worrying about the first two. Another useful move is to comment out a block and see whether the bug remains. If it remains, that block is probably not the cause. If it disappears, the cause is inside that block, and you can narrow further inside it.
A checklist you can use every time
- Write down what the program should do and what it actually does, in one sentence each.
- Find the smallest input that still shows the bug, and keep that input as your test.
- Read the error message from the last line, and open the line it points to.
- Print the values at the points where the result could first go wrong.
- Change one thing, run the test again, and note whether the result changed.
- When the test passes, run the program with other inputs, including an empty input and a single value.
- Remove debug prints, and re-read the changed code before you move on.
Common mistakes to watch for
Changing many things at once is the most common debugging mistake. It feels productive, because the code moves, but it destroys the evidence. If the bug disappears, you do not know which change fixed it, and you may have added a new bug while fixing the old one. Change one thing, test, and only then move to the next idea.
Guessing from the error name alone is another trap. A NameError, for example, can mean a spelling mistake, a variable used before it is set, or a name from another scope that is not available in that spot. The error name narrows the search, but it does not finish it. Open the line, check the name, and check where that name was set, before you change anything.
Ignoring the input is a third trap. Many bugs live in the data, not in the code. A program that works for numbers may fail for text, a program that works for a full list may fail for an empty one, and a program that works for one user may fail for another. The functions guide shows how inputs flow into a function, and the first program guide shows how a small test program can check one function on its own. When a bug resists every code change, check the input again with fresh eyes.
Limits of this guide
This guide covers bugs in a short program that you can run and read in full. It does not cover bugs that only appear under load, bugs in code you cannot run locally, or bugs that involve two systems talking to each other, because those cases need logging, monitoring, and tools beyond a first guide. It also does not cover writing automated tests, which is the next step once debugging becomes a regular part of your work. A test that reproduces a bug, and stays in the project, stops the same bug from returning unnoticed after a later change.
Worked example: find a wrong total step by step
A program that runs without an error, yet gives a wrong answer, is a logic bug, and it needs a different approach from a crash. The example below should add prices and print a total, yet it prints a total that is too low. The code has no error message to point at, so the fix must come from checking values at each step, rather than from reading a traceback.
prices = [12, 8, 5]
total = 0
for price in prices:
total = price
print(total)
The bug is on the line inside the loop. It replaces total with each price, instead of adding each price to total, so the final total is simply the last price, 5. A print call inside the loop would show total taking the values 12, 8, then 5, which reveals the pattern at once. The fix is to change the line to total = total + price, which accumulates the sum across passes.
That example shows a useful rule for logic bugs. Do not guess at the fix and run the whole program again. Print the value at the point where it first looks wrong, and compare it with the value expected by hand. The first place where the actual value differs from the expected value is close to the bug, and it narrows the search to a small part of the code.
Use print tracing, then a debugger, in that order
Print tracing means adding print calls that show values at key points, running the program, and removing the prints once the bug is found. It is fast, it needs no setup, and it works in any program, which is why it is the first tool for most beginners. Its weakness is that a program with many prints becomes noisy, and the prints themselves must be removed afterward, or they clutter later output.
A debugger lets the program pause at a chosen line, called a breakpoint, so the reader can inspect values at that moment and step through the code line by line. That control suits a bug where the wrong value appears after several steps, because the reader can watch the value change across those steps without adding prints. The Python debugger, pdb, is built in, and many editors offer a visual debugger with the same pause and step ideas.
| Tool | Strength | Weakness |
|---|---|---|
| Print tracing | Fast, no setup, works anywhere | Noisy, prints must be removed later |
| Debugger | Pause, inspect, step line by line | Needs a breakpoint and some setup |
| Reading code | Finds logic errors prints may miss | Slow on a long program |
A practical workflow uses print first for a quick check, and a debugger when the print output does not narrow the bug enough. That order keeps the simple tool for simple bugs, and saves the heavier tool for bugs where watching values change across steps is the fastest way to understand what the program actually does.
Isolate the problem with a smaller case
Isolating a bug means shrinking the program until the bug still appears in the smallest possible form. If a bug appears with a list of twenty items, try it with three items, then with two, then with one. The smallest case that still shows the bug is easier to trace, and it often reveals the pattern that the larger case hid, such as a bug that only appears on the last item or on an empty list.
Another isolation technique is to comment out half the program, or to replace a suspect part with a fixed value, and to check whether the bug remains. When the bug disappears after removing a part, that part is involved in the bug, and the search narrows to it. When the bug remains, that part is cleared, and the search moves elsewhere. That halving process finds a bug faster than reading the whole program from the top each time.
Writing a tiny separate program that reproduces the bug is also valuable, because it proves the bug is in the suspect code rather than in the surrounding program. That tiny program can then be shared when asking for help, because it shows the bug without the reader needing to run a whole project. A helper who can run the tiny program can often spot the fix in minutes, while a whole project takes far longer to understand.
When a fix works, check that it did not break another case
A fix that solves one case can break another, especially when the fix changes a condition or a boundary. After fixing a bug, rerun the program with the original failing case, with a normal case, and with a boundary case, such as an empty list or a zero value. That small set of reruns catches the common pattern where a fix for one input shifts the problem to a neighbouring input.
Keeping a short note of the bug and its fix helps here. Write down what the symptom was, what the cause turned out to be, and what changed to fix it, in a few lines beside the code or in a project note. That note saves time when a similar symptom appears later, because the earlier cause becomes the first thing to check, rather than a puzzle to solve from scratch.
When a bug keeps returning after several fixes, the problem may be in the design rather than in one line. A function that tries to do too much, or a variable that changes meaning halfway through a program, will keep producing bugs in new places. In that case, splitting the function or giving the variable a clearer name is a better fix than patching the next symptom, because it removes the source of confusion that keeps creating bugs.
Frequently asked questions
Should I use a debugger or print statements to find a bug?
Print statements are enough for a short program, because they show values at chosen points with little setup. A debugger is better when a program is long or when a value changes in a place you cannot see, because it lets you pause and inspect values step by step. Start with prints, and learn a debugger when prints stop being enough.
When should I ask someone else for help with a bug?
Ask after you can describe what the program should do, what it actually does, and what you have already tried. That description often helps you see the bug yourself, and it gives the other person a clear starting point. Asking with only a screenshot of an error, and no description, usually leads to more questions than answers.
How long should I stay stuck on one bug before I step back?
If you have tried two or three clear ideas and none of them changed the result, step back and re-read the problem in plain words. A short break, or explaining the code out loud in order, often reveals an assumption you made without noticing. Returning with a fresh test, rather than a new guess, is usually more useful than pushing on with the same approach.
What is a breakpoint, and how do I use one?
A breakpoint is a line where a debugger pauses the program, so values can be inspected at that moment. Set a breakpoint on the line before the suspected bug, run the program in debug mode, and step through the following lines while checking each value.
How do I shrink a bug to a smaller case?
Try the failing input with fewer items, then fewer again, until the smallest case that still shows the bug remains. That small case is easier to trace, and it often reveals a pattern hidden in the larger case.
How do I check a fix did not break another case?
Rerun the program with the original failing case, a normal case, and a boundary case such as an empty list or zero. That small set catches fixes that solve one input while shifting the problem to a neighbouring input.


