
Learn to Program in the Age of AI, Part 4: Debugging Without Handing Everything to the AI (2026)
Your code fails, so you paste the error into an AI assistant, copy the fix, and move on. It works, so what is the problem?
The problem is what you did not learn. You do not know why it failed, so you cannot spot the same mistake next time. You also cannot tell when the AI’s fix is wrong. Debugging is the skill that AI use erodes fastest, and it is the one you need most when AI-written code breaks.
This is the fourth article in my series for beginners, career switchers, and junior developers who already use AI tools. Part 1 explained which skills still matter. Part 2 showed how to use AI as a tutor. Part 3 gave you a checklist for reviewing AI code. This part is about what to do when the code does not work.
As always, I tested it. I gave a local AI model ten failing functions and asked for fixes in three different ways. The results surprised me. Simple bugs got fixed even from “it doesn’t work”. The trouble started when the code could not say what I meant, and then the way I asked decided everything. I also tested a prompt that asks for hints instead of fixes. The research I cite comes from Anthropic’s published study and the Python documentation, which I checked on December 1, 2026.
The series
- What still matters
- Using AI as a tutor, not a ghostwriter
- Reading and reviewing AI-generated code
- Debugging without handing everything to the AI (this article)
- Testing as your safety net
- Your first project with an agent
Table of Contents
- The Short Answer
- Why Debugging Is the Skill to Protect
- A Worked Example: Six Steps on a Real Bug
- Reading a Traceback
- Experiment 1: Simple Bugs and “It Doesn’t Work”
- Experiment 2: When the Code Cannot Say What You Meant
- The Bug Report Template
- Experiment 3: Ask for a Hint, Not a Fix
- Rules for Debugging With AI
- Practice: Write the Report, Then Debug
- Common Mistakes
- Frequently Asked Questions
- Conclusion
- References
1. The Short Answer
Debugging is a loop of six steps. Each one has a job, and the first three are exactly what a good bug report contains.
| Step | What you do | In the worked example |
|---|---|---|
| 1. Reproduce | Run it again and get the same failure | Both totals print as 62.1 |
| 2. Minimize | Shrink the input until only the problem remains | One item, one 10% discount |
| 3. Observe | Print or inspect values near the suspect | The original price changed from 10.0 to 9.0 |
| 4. Hypothesize | Write one guess that an experiment can prove wrong | “apply_discount edits the original items” |
| 5. Test and fix | Check the guess, then change one thing | discounted is items prints True |
| 6. Lock it in | Add a test that fails before the fix and passes after | One of three tests failed on the buggy code |
Here is what the three experiments found, using Gemma 4 (gemma4:e4b) running locally.
| Experiment | What I tested | Result |
|---|---|---|
| 1. Simple bugs | Six functions with visible bugs, asked about three ways | 36 of 36 fixed, even from “it doesn’t work” |
| 2. Hidden intent | Four functions where the code cannot say what I wanted | Vague 4 of 12, concrete example 11 of 12, full bug report 12 of 12 |
| 3. Hints | A prompt asking for one hint and no code | 6 of 6 replies were a single question of 10 to 16 words |
The vague requests failed in a telling way. All eight failures told me my original code was correct, and seven of them handed it back unchanged.
The lesson is not that AI cannot debug. It is that the AI cannot see what you intended, so you must say it. Writing that down is also most of the debugging.
2. Why Debugging Is the Skill to Protect
Anthropic published a randomized study on January 29, 2026, which I summarized in Part 1. Mostly junior developers learned a new Python library, some with an AI assistant and some without. The AI group scored lower on the follow-up quiz, 50% against 67%. The largest gap was on debugging questions.
The study also grouped people by how they used the assistant, as Part 2 explains. One pattern is directly about this article. Participants who let the AI fix each error in turn, which the researchers called iterative AI debugging, averaged below 40% on the quiz. Participants who asked conceptual questions, or who asked for code together with explanations, scored 65% or higher.
That matches what you feel in practice. If the AI always finds the bug, you never build the instinct for where bugs hide. Then one day the AI is wrong, or unavailable, or confidently tells you your code is fine. You need the skill most at the moment you have practiced it least.
There is a second reason. An AI assistant sees only what you paste. It does not know what you meant, what data you have, or which version you run. Debugging well means collecting those facts, and that is a human job.
3. A Worked Example: Six Steps on a Real Bug
Here is a small invoice program. It parses order lines, applies a percentage discount, and prints two totals.
def parse_line(line):
name, qty, price = line.split(",")
return {"name": name, "qty": int(qty), "price": float(price)}
def apply_discount(items, percent):
for item in items:
item["price"] = item["price"] * (1 - percent / 100)
return items
def total(items):
return round(sum(i["qty"] * i["price"] for i in items), 2)
def invoice(lines, percent=0):
items = [parse_line(line) for line in lines]
discounted = apply_discount(items, percent)
print("Subtotal:", total(items))
print("After discount:", total(discounted))
if __name__ == "__main__":
invoice(["pen,10,1.50", "book,2,12.00", "bag,1,30.00"], percent=10)
Before running it, decide what it should print. The pens cost 15.00, the books 24.00, and the bag 30.00, so the subtotal should be 69.00. With 10% off, the discounted total should be 62.10.
Step 1: Reproduce
Run it and read the output.
Subtotal: 62.1
After discount: 62.1
Both lines are the same, which is wrong. The second line is correct, but the subtotal should be 69.0. Running it again gives the same output, so the bug is reproducible. A bug you cannot reproduce is a bug you cannot test a fix against.
Step 2: Minimize
Three items and a 10% discount make the arithmetic hard to follow. Shrink the input until you cannot remove anything more.
from invoice import invoice
invoice(["pen,1,10.00"], percent=10)
Subtotal: 9.0
After discount: 9.0
Now the expected result is obvious: a subtotal of 10.0 and a discounted total of 9.0. One item, one number, one clear mismatch. Minimizing also tells you what does not matter. The bug does not need three items or any particular names.
Step 3: Observe
Do not guess yet. Look at the real values. The total function is three lines and looks fine, so the suspect is apply_discount. Print the items before and after calling it.
from invoice import parse_line, apply_discount, total
items = [parse_line("pen,1,10.00")]
print("before:", items, total(items))
discounted = apply_discount(items, 10)
print("after: ", items, total(items))
print("same object:", discounted is items)
before: [{'name': 'pen', 'qty': 1, 'price': 10.0}] 10.0
after: [{'name': 'pen', 'qty': 1, 'price': 9.0}] 9.0
same object: True
Notice what changed: the variable items was never reassigned, yet its price went from 10.0 to 9.0. Something changed the original list from the inside.
Step 4: Form one hypothesis
State it as a sentence that an experiment could prove wrong: “apply_discount edits the dictionaries inside items in place, and returns the same list, so the original is discounted too.” The output above already supports it. The line same object: True shows that discounted and items are one list.
A debugger shows the same facts. Python’s built-in breakpoint() stops the program and opens pdb, where p prints a value and c continues. I put breakpoint() after the call and typed three commands. The file path is shortened below.
> min3.py(4)<module>()
-> breakpoint()
(Pdb) p discounted is items
True
(Pdb) p items
[{'name': 'pen', 'qty': 1, 'price': 9.0}]
(Pdb) p items[0]["price"]
9.0
(Pdb) c
Print statements and a debugger do the same job. Start with prints, and move to a debugger when you want to look at many values without editing the code each time.
Step 5: Test and fix, one change at a time
The hypothesis predicts that building new dictionaries instead of editing the old ones will fix it. That is one change.
def apply_discount(items, percent):
return [{**item, "price": item["price"] * (1 - percent / 100)} for item in items]
Running the original program now prints the right answer.
Subtotal: 69.0
After discount: 62.1
This is one of several valid fixes. You could also call copy.deepcopy(items) and edit the copy, or copy each dictionary with item.copy() before editing it. Copying only the list, with list(items), does not work. The dictionaries inside are still shared, so the original prices still change. I tested all three versions.
Step 6: Lock it in with a test
A fix without a test is a fix you will have to redo. Write a test from the minimal case, and run it against the buggy code first. A test that has never failed proves nothing.
import unittest
from invoice import apply_discount, parse_line, total
class DiscountTests(unittest.TestCase):
def test_discount_does_not_change_the_original_items(self):
items = [parse_line("pen,1,10.00")]
apply_discount(items, 10)
self.assertEqual(total(items), 10.0)
def test_discount_returns_the_reduced_total(self):
items = [parse_line("pen,1,10.00")]
self.assertEqual(total(apply_discount(items, 10)), 9.0)
def test_zero_percent_changes_nothing(self):
items = [parse_line("pen,2,5.00")]
self.assertEqual(total(apply_discount(items, 0)), 10.0)
Against the buggy code, the result was FAILED (failures=1). The failure was AssertionError: 9.0 != 10.0 in the first test. After the fix, all three pass.
Only the right question caught the bug. Two of the three tests passed on the buggy code. Only the test that checked the original items after the discount failed. A test suite is only as good as the questions in it.
The bug also did not live where the symptom appeared. The wrong number showed up in a print line, while the cause was in a different function. That distance is why guessing is slow and observing is fast. Part 5 of this series goes deeper on writing tests like these.
4. Reading a Traceback
When a program crashes, Python prints a traceback. Beginners often skip it, and AI users often paste it without reading it. It tells you most of what you need. Here is a real one from a word counter, with the file paths shortened.
Traceback (most recent call last):
File "main.py", line 8, in <module>
print(count_words(["a", "b", "a"]))
~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "main.py", line 4, in count_words
counts[w] += 1
~~~~~~^^^
KeyError: 'a'
Read it from the bottom up.
- The last line says what happened.
KeyError: 'a'means the code asked a dictionary for the key'a', and the key was not there. - The frame above it says where. Line 4, in
count_words, on the statementcounts[w] += 1. In recent Python versions, the^^^marks under the line point at the exact part that failed, here[w]. - The frames above that say how you got there. Here, line 8 called
count_words.
Now form the hypothesis. counts starts empty, so the first time a word appears, counts[w] does not exist yet. You can test that in one line by printing counts before the loop. The usual fix is counts[w] = counts.get(w, 0) + 1.
A traceback is a report written by Python. When you ask an AI for help, include the whole thing, not just the last line.
5. Experiment 1: Simple Bugs and “It Doesn’t Work”
I wanted to know whether the way you ask matters. I wrote six small functions, each with one classic beginner bug, and asked Gemma 4 (gemma4:e4b) to fix them.
| Function | The bug |
|---|---|
remove_negatives |
Removes items from a list while looping over it, so neighbors get skipped |
count_words |
Adds to a dictionary key that does not exist yet |
parse_date |
Reads day/month/year text with a month/day/year format |
sort_versions |
Sorts version numbers as text, so "1.10" comes before "1.9" |
average_last |
A slice, nums[-n:-1], that stops one item short |
total_price |
Replaces the total on every pass instead of adding to it |
For each bug, I asked for help three ways. The code was pasted each time.
- Vague: “My
remove_negativesfunction doesn’t work properly. Can you fix it?” - Symptom: “When I run
remove_negatives([-1, -2, 3])I get[-2, 3].” - Report: The minimal case, the expected result, the actual result, and what I checked, as in section 7.
Each request ran twice, which gave 36 replies. I graded every reply with hidden tests, running the model’s code in a separate process. I also confirmed that the tests fail on the original buggy code, with between two and four failing tests per function. A grader that passes everything would tell me nothing.
What happened
All 36 replies fixed the bug. Vague, symptom, and report each scored 12 of 12. The median reply length was 296 words for vague, 254 for symptom, and 232 for the report. My check also found no reply that hid the error behind an except block.
My first grader reported only 28 of 36. It matched function names by prefix, so a helper called remove_negatives_while was run instead of the real function. Reading the raw replies exposed it, and I regraded the saved replies after fixing it. When a result looks odd, read the raw output and check the checker.
What this tells you
When the cause is visible in the code, a capable model finds it from almost any request. That is good news, and it is also a trap. If “it doesn’t work” always works, you stop practicing the harder skill. The model also often gave you several versions at once. Eight of the 36 replies contained more than one version of the function, which is more for a beginner to read, compare, and choose between.
6. Experiment 2: When the Code Cannot Say What You Meant
Real bugs are often not visible in the code. The code is valid and does something reasonable. It just is not what you wanted. I wrote four of those.
| Function | What the code does | What the user wanted |
|---|---|---|
unique_in_order |
list(set(items)) |
Each value once, in the order it first appeared |
round_score |
round(x) |
Halves always round up, so 2.5 becomes 3 |
days_between |
Subtracts two dates | Both the first and the last day count |
paginate |
start = page * size |
Page numbers that start at 1 |
Python rounds halves to the nearest even number, so round(2.5) is 2 and round(1.5) is 2. The Python documentation describes this behavior.
I used the same three ways of asking. For round_score, they looked like this.
- Vague: “My
round_scorefunction doesn’t work properly. Can you fix it?” - Symptom: “When I run
round_score(2.5)I get 2.” - Report: The four lines below.
Minimal case: round_score(2.5)
Expected: 3
Actual: 2
What I checked: round_score(3.5) returns 4, but round_score(0.5) returns 0.
In my app, a value exactly halfway must always round up.
Each request ran three times, which gave 36 replies. I graded them with hidden tests that encode the intent, after checking that every test set fails on the original code.
The scores
| How I asked | Fixed | Median reply length |
|---|---|---|
| Vague | 4 of 12 | 351 words |
| Symptom | 11 of 12 (12 if the renamed fix counts) | 298 words |
| Report | 12 of 12 | 269 words |
Per function, the picture is more specific.
| Function | Vague | Symptom | Report |
|---|---|---|---|
unique_in_order |
3/3 | 3/3 | 3/3 |
round_score |
0/3 | 3/3 | 3/3 |
days_between |
0/3 | 2/3 | 3/3 |
paginate |
1/3 | 3/3 | 3/3 |
I read the failures instead of trusting the count. The one symptom miss was a correct fix under a new name. The model returned days_between_inclusive, which passes my tests when renamed. Counted generously, the symptom result is 12 of 12.
How the vague requests failed
When the request was vague, the model defended my code. All eight failures said the original was correct, and seven returned it unchanged. The code was not wrong. The model simply had no way to know what I wanted.
Several replies also asked what input I was using and what output I expected, which is a fair question that I had not answered.
For paginate, the model explained that the function was logically correct for zero-based page numbers. That is true, but it was not what I wanted, and nothing in the code said so.
One function was fine even from a vague request. For unique_in_order, the model guessed that a set having no order was the problem. When the likely intent is guessable, vague works. When it is not, as with round_score, days_between, and paginate, the model has nothing to go on.
What this does and does not show
The result is small and has limits. It used one small local model, three runs per request, and four functions. Larger models may guess intent better, and I did not test them. The gap between symptom and report is one run, and it is a renamed function, so I cannot claim that the extra lines of the report mattered for correctness.
What the data does support is simple. Giving the AI one concrete case, with the input and what you got, turned 4 of 12 into 11 or 12 of 12. Adding what you expected gave 12 of 12, though the difference is one renamed function. Either way, it costs you a minute.
The learning benefit is an argument, not something I measured. You cannot fill in “What I checked” without checking something. The report forces steps 1 to 3 of the method. Even if the AI never reads it, writing it is debugging.
7. The Bug Report Template
Use this whenever you ask a person or an AI for debugging help.
Minimal case: the smallest call or input that fails
Expected: what you wanted, and why
Actual: exactly what happened, including the full error
What I checked: what you printed or tried, and what it showed
My guess: one hypothesis, if you have one
Environment: language version, operating system, anything unusual
Each line earns its place.
- Minimal case: It proves you reproduced the problem and removes noise.
- Expected: This is the line the AI cannot guess. It carries your intent, which the code cannot.
- Actual: Paste the output exactly. Do not paraphrase an error message.
- What I checked: It shows what you have already ruled out, so the answer does not repeat it.
- My guess: It gives the AI something to confirm or challenge. A wrong guess is still useful, because “no, because…” teaches you something.
- Environment: Version differences cause real bugs, such as a function that exists in one Python version and not another.
My experiments tested the first four lines. I did not test “My guess” or “Environment”, so treat those as sensible habits rather than measured results.
8. Experiment 3: Ask for a Hint, Not a Fix
The best-scoring patterns in the Anthropic study kept the person thinking. For debugging, that means asking for a hint. I tested whether a model follows that instruction. I gave it the buggy invoice program from section 3, a bug report, and this request.
I am learning to debug, so please do not fix this for me. Do not write any
corrected code. Give me ONE hint, written as a question I can answer by
running or printing something. Do not name the cause. If I answer wrongly,
I will come back for the next hint.
I ran it six times.
The result
All six replies were a single question of 10 to 16 words. None contained code, and none named the cause. Here is one of those replies.
What do the values of
itemsanddiscountedlook like right before theprint("Subtotal:", total(items))line?
That is a good hint. Answering it means printing items and noticing that its price has already changed. Five of the six replies pointed at the right moment, either right before the subtotal line or at the list used to calculate it. One asked about items before apply_discount runs. That list looks correct, so the hint would tell you little, and you would come back for the next one.
For comparison, the normal fix requests in the earlier experiments had median replies of 230 to 350 words.
A ladder to climb
This is a suggestion, not a tested method. It follows the pattern of the high-scoring groups in the study.
- Ask for one hint, as a question you answer by running something.
- Answer it, and ask for the next hint if you are still stuck.
- State your hypothesis and ask the AI to challenge it: “I think the function edits the original list. What would show whether I am wrong?”
- Ask for the cause only after you have tried, and explain it back in your own words.
- Ask for the fix last, and ask why it works.
Part 2 has a tutor prompt you can adapt. One small bug and six runs show that a model can follow a no-code instruction. Try it on your own code before relying on it.
9. Rules for Debugging With AI
- Try first: Spend fifteen minutes on the bug yourself before asking, as in Part 1. Reproducing and minimizing take only a few of them.
- Never send “it doesn’t work”: In my experiment, that request made the AI defend correct-looking code.
- Believe your evidence over the AI: If the AI says your code is fine and it still fails, you have a failing case. The AI does not.
- Do not ask the same thing again: Part 3 showed that a model’s gaps repeat. Change the information you give instead.
- Explain the cause in your own words: If you cannot, you have a patch, not a fix.
- Distrust fixes that hide errors: An
exceptblock that returns an empty list silences the symptom and keeps the bug. - Test the original failing case: Then keep it as a test, so the bug cannot come back unseen.
- Change one thing at a time: If you change three things and it works, you do not know which one mattered.
10. Practice: Write the Report, Then Debug
For each program, do three things before looking at the answers. Write the four-line bug report, form one hypothesis, and decide what one-line check would test it.
Exercise 1
You want a 3 by 3 grid of zeros, and then you set the top-left cell to 5.
grid = [[0] * 3] * 3
grid[0][0] = 5
print(grid)
It prints [[5, 0, 0], [5, 0, 0], [5, 0, 0]]. You expected only the first row to change.
Exercise 2
You want the largest number in a line of text.
line = "9 10 100"
numbers = line.split()
print(max(numbers))
It prints 9, but you expected 100.
Answers
Exercise 1 answer
Minimal case: grid = [[0] * 3] * 3, then grid[0][0] = 5
Expected: [[5, 0, 0], [0, 0, 0], [0, 0, 0]]
Actual: [[5, 0, 0], [5, 0, 0], [5, 0, 0]]
What I checked: grid[0] is grid[1] prints True
The hypothesis is that * 3 repeats the same row object three times, so all three rows are one list. The check in the last line confirms it. This is the same family of bug as the invoice example: two names for one object. The fix builds three separate rows, and I ran it to confirm the output.
grid = [[0] * 3 for _ in range(3)]
That prints [[5, 0, 0], [0, 0, 0], [0, 0, 0]].
Exercise 2 answer
Minimal case: max("9 10 100".split())
Expected: 100
Actual: 9
What I checked: "9" > "10" prints True
The hypothesis is that split() returns strings, and strings compare character by character, so "9" beats "10" because "9" is greater than "1". The fix converts to numbers first. I ran it, and it prints 100.
numbers = [int(n) for n in line.split()]
If you wrote a report with a minimal case and a check that proved the cause, you did the main skill of this article. That already puts you ahead of “it doesn’t work”.
11. Common Mistakes
- Debugging the full input: Minimize first, because a small case is easier to reason about.
- Guessing before observing: Print or inspect values, then form a hypothesis from what you see.
- Changing several things at once: You will not know what fixed it.
- Pasting only the last line of an error: The frames above it say where and how.
- Sending “it doesn’t work” to an AI: It cannot see your intent, so it may defend your code.
- Accepting a fix you cannot explain: The same bug will return in a different shape.
- Silencing errors: A bare
excepthides the symptom and leaves the cause. - Skipping the regression test: Without it, you cannot tell that the bug stayed fixed.
12. Frequently Asked Questions
Should I use print statements or a debugger?
Start with prints, because they are quick and work everywhere. Use a debugger when you want to inspect many values or step through code line by line. In Python, breakpoint() opens the standard debugger at that line, with no import needed on current versions.
What if there is no error message, only wrong output?
That was the invoice example. Without a traceback, your expected and actual values are the whole report. Minimize first, then print values until reality differs from what you expected.
How long should I try before asking an AI?
About fifteen minutes is a good starting rule, as Part 1 suggests. The goal is not suffering. It is to do the reproduce and minimize steps yourself, which makes any later question better.
Does this apply to AI agents that run my code?
The same habits apply, though I did not test agents in this experiment. Ask an agent to reproduce the failure first, and to add a test that fails before the fix. Part 6 tests agents directly.
Would a bigger model behave differently?
Probably better at guessing intent, but I did not test one. The underlying problem stays the same. A model cannot see what you meant unless you say so, and your own understanding of the cause is what you keep.
Is hint-only prompting slower?
Yes, for that bug. It is also the point. The slow part is where you learn, and the high-scoring patterns in the Anthropic study all kept the learner engaged with the problem.
13. Conclusion
Debugging is a loop you can learn: reproduce, minimize, observe, hypothesize, test one fix, and lock it in with a test. The first three steps are also a bug report, and a bug report is what makes an AI useful.
My experiments showed both sides. On simple bugs, the model fixed everything, even from “it doesn’t work”. When the code could not say what I meant, vague requests worked in 4 of 12 runs, and every failure told me my code was fine. A concrete example got that to 11 of 12, and a full report to 12 of 12. A hint-only prompt returned one short question every time, with no code.
So keep the debugging, and use the AI to sharpen it. Write the report, ask for hints, and explain every fix back in your own words. The next article covers testing: how to write tests first, let the AI implement them, and measure what your tests actually catch. Tools and guidance change, so treat the specifics here as accurate as of early December 2026.
14. References
Research
- Anthropic: How AI assistance impacts the formation of coding skills (January 2026)
- Shen and Tamkin: the study paper on arXiv
Python documentation
- Python:
pdb, the Python debugger - Python: the built-in
breakpoint()function - Python: the built-in
round()function - Python:
unittest, the unit testing framework - Python tutorial: errors and exceptions
- Python tutorial:
forstatements and modifying a collection
On this site
- Part 1: What still matters
- Part 2: Using AI as a tutor, not a ghostwriter
- Part 3: Reading and reviewing AI-generated code