Sub topic 9
Debugging with AI Without Handing Over the Thinking
This chapter assumes you can run a Python script and a simple test, that you have used a chat assistant before, and that you have read the earlier chapters on the attempt-first workflow and on checking AI code with your own tests. Here the focus is on bugs: how to use an AI to find them without giving up the reasoning that makes you better at finding them.
Why debugging is where skill is built
Writing new code is only part of programming. Much of the work is reading code that does not behave as expected and working out why. That work trains a specific set of skills:
- Predicting what a piece of code should do.
- Noticing where reality differs from the prediction.
- Forming a guess about the cause.
- Designing a small check that could prove the guess wrong.
If you paste an error into an AI and apply whatever fix comes back, you skip all four. The bug disappears, but you still can't find the next one without help. This is the same gap described at the start of the tutorial: working code is not the same as learning.
The aim is not to avoid AI when debugging. The aim is to keep the hypothesis-and-test loop in your hands and to use the AI as a source of questions, hints and second opinions.
The debugging loop you own
A reliable loop has five steps. You do the first four before the AI offers any diagnosis.
- Reproduce. Find the smallest input that makes the bug appear, and make it happen every time.
- Predict. Write down what you expected and what you actually got.
- Hypothesize. State one specific guess about the cause, for example "the loop skips the last element".
- Test the guess. Add a
print, an assertion or a debugger breakpoint that would confirm or refute the guess. - Fix and verify. Change the code, then run the reproduction and a test that guards against the bug returning.
The AI enters at the "stuck" branch, and even there it returns you to the hypothesis step instead of replacing the loop.
A worked example
Suppose you wrote a function to compute a moving average, the mean of each window of k consecutive values. It runs without errors but returns the wrong numbers.
def moving_average(values, k):
result = []
for i in range(len(values) - k):
window = values[i:i + k]
result.append(sum(window) / k)
return result
print(moving_average([1, 2, 3, 4, 5], 2))Step 1 and 2: reproduce and predict
For [1, 2, 3, 4, 5] with k = 2, the windows are [1,2], [2,3], [3,4] and [4,5]. You expect [1.5, 2.5, 3.5, 4.5]. Running the code prints [1.5, 2.5, 3.5]. You have a concrete difference: one value is missing, and it is the last one.
Step 3: hypothesize
"The output has one fewer item than expected, and the missing item is at the end, so the loop probably stops one index too early." That is a specific, testable statement. A vague guess such as "something is wrong with the loop" can't be tested.
Step 4: test the guess
Print the indices the loop visits.
values = [1, 2, 3, 4, 5]
k = 2
print(list(range(len(values) - k)))This prints [0, 1, 2]. The last window starts at index 3, so the hypothesis holds. The number of windows is len(values) - k + 1, not len(values) - k.
Step 5: fix and verify
def moving_average(values, k):
if k <= 0 or k > len(values):
raise ValueError("k must be between 1 and len(values)")
result = []
for i in range(len(values) - k + 1):
window = values[i:i + k]
result.append(sum(window) / k)
return result
assert moving_average([1, 2, 3, 4, 5], 2) == [1.5, 2.5, 3.5, 4.5]
assert moving_average([1, 2, 3], 3) == [2.0]
assert moving_average([7], 1) == [7.0]
try:
moving_average([1, 2], 5)
except ValueError:
pass
else:
raise AssertionError("k larger than the list should raise ValueError")Notice that the fix reaches beyond the single line. The case k == len(values) is the boundary where the original bug would have returned an empty list, so it gets its own assertion. Writing that test is part of understanding the bug, not decoration.
Where the AI fits
Use the AI at specific points, and ask for specific things.
| Situation | What to ask for | What to avoid |
|---|---|---|
| You can't reproduce the bug reliably | Ways to shrink the input or capture the failing case | Asking it to "fix my program" |
| You have no hypothesis | One guiding question about the symptom | A full diagnosis |
| You have a hypothesis but can't test it | Options for a check, such as a `print`, an assertion or a debugger breakpoint | Asking it to run the reasoning for you |
| You don't understand an error message | An explanation of the message in plain words | A rewritten program |
| You have a fix | A review of the fix and of missing edge cases | Accepting its approval as proof |
A prompt that keeps the thinking with you
Compare two prompts for the moving-average bug.
The first hands over everything: "My moving average is wrong, fix it." The reply will usually be a corrected function. You learn nothing about off-by-one errors in range.
The second keeps the loop yours:
I am debugging a Python function. Do not give me the corrected code.
Expected: moving_average([1, 2, 3, 4, 5], 2) returns [1.5, 2.5, 3.5, 4.5]
Actual: it returns [1.5, 2.5, 3.5]
My hypothesis: the loop stops one index too early.
What I tried: I printed range(len(values) - k) and got [0, 1, 2].
Is my hypothesis consistent with this evidence? If it is, ask me one question that leads me to the correct number of windows. If it is not, give me one hint toward a better hypothesis.This prompt contains the expected result, the actual result, your own hypothesis and the evidence you gathered. It also states what kind of reply you want. An AI given this context can check your reasoning, and you stay the one who decides the cause.
Stating your hypothesis first
Writing the hypothesis before asking has a second benefit beyond a better reply. If you can't write it, you have found out something useful: you do not yet understand the symptom. Go back to step 2 and look at the actual and expected outputs again.
Failure modes when debugging with AI
AI debugging help goes wrong in recognizable ways. Watch for these.
- A confident wrong diagnosis. The AI sees code and a symptom and names a cause that sounds right but does not match your evidence. Always test its claim with a check, the same as you would test your own.
- Fixing the symptom. A reply may add a special case, such as returning an empty list when the input is short, so the visible failure goes away while the logic stays wrong. Ask: does this change explain why the original output was wrong?
- Changing too much. If the reply rewrites the whole function, you can't tell which change mattered. Prefer one change at a time, and rerun your reproduction after each.
- Lost context. The AI sees only what you paste. A bug caused by data, configuration or an earlier call that you did not include will lead it to guess.
- Agreeing with your wrong hypothesis. Assistants tend to go along with what you state. Ask directly: "What evidence would show my hypothesis is wrong?"
Deciding when to ask
Struggle is useful, but unlimited struggle is not. Set a limit before you start, for example 20 minutes or three refuted hypotheses, whichever comes first. When you reach it, ask for a question or hint, not a solution. If the hint doesn't help, ask for a stronger one. Move to a full fix only after you have an hypothesis of your own to compare it against, and then study the difference between the AI's cause and yours.
Some cases call for a faster ask:
- An unfamiliar tool or environment problem, such as a failing install, where there is little reasoning to learn from the specific bug.
- A bug in code you did not write and don't need to master.
- A situation where a deadline matters more than the lesson. Note the bug and revisit it later when you can.
Keeping a bug log
After each bug, write down three lines in a notes file:
- The symptom, in the form "expected X, got Y".
- The cause, in one sentence.
- The check that revealed it.
Over a few weeks the log shows patterns, such as repeated off-by-one errors or mutating a list while looping over it. Those patterns tell you what to practice, and they feed the unaided checks covered in the last chapters of this tutorial.
Exercise
The function below should return the largest value in a non-empty list, but largest([-5, -2, -9]) returns 0. Write down (a) the expected and actual output, (b) one hypothesis, and (c) one check that could refute your hypothesis. Then write a prompt that asks an AI to review your hypothesis without giving you the fixed code.
def largest(values):
best = 0
for v in values:
if v > best:
best = v
return best
Show answer
(a) Expected -2, actual 0. (b) The starting value best = 0 is larger than every item when all values are negative, so it is never replaced. (c) Print best before the loop and after each comparison, or call largest([-1]) and check that it returns 0 instead of -1. A suitable prompt: "I am debugging a Python function that should return the largest value in a list. Expected: largest([-5, -2, -9]) returns -2. Actual: it returns 0. My hypothesis: best starts at 0, which is bigger than all the values. My check: largest([-1]) returns 0. Do not give me the corrected code. Is my hypothesis consistent with this evidence, and what should I think about for the starting value?" The fix is to start from values[0], with an explicit error for an empty list.
Exercise
An AI replies to your bug report by adding if not result: return [0] to moving_average and says this fixes the problem. List two questions you would ask before accepting this change.
Show answer
First, does the change explain why the original output was wrong? A special case for an empty result hides the symptom without correcting the window count. Second, what does the test suite say? Run the reproduction moving_average([1, 2, 3, 4, 5], 2) and a boundary test such as moving_average([1, 2, 3], 3). If either still gives a wrong answer, the change masked the bug. You could also ask why [0] is a correct answer for an empty input, since it invents a value that is not in the data.