Debugging Python Code with AI
Beginner programmers spend more time stuck on errors than writing new code. This used to mean googling cryptic error messages, scrolling Stack Overflow, and copy-pasting solutions you did not understand. AI changes that — if you debug with it the right way.
The wrong way is to paste an error and ask "fix this." The right way is to share the full picture, ask for a diagnosis first, and then verify the fix.
What You'll Learn
- The DIAGNOSE → FIX → VERIFY debugging loop
- A debugging prompt that prevents AI from "fixing" the wrong thing
- Common Python error messages decoded
- When to trust AI's fix and when to push back
The Three Pieces of Information You Always Share
When you ask AI to debug Python, give it all three of these. Every single time.
1. The full error message. Not a summary, not "it gave an error" — the entire traceback from the line that says "Traceback (most recent call last):" down to the last line. The traceback tells the AI which line failed and what kind of error.
2. The full code that produced it. Not just the failing line. The AI needs the surrounding context.
3. What you expected to happen. This is the step beginners skip. AI does not know what your code was supposed to do. Without that, it cannot tell whether the fix is correct.
Here is a prompt template you can paste directly:
I am a beginner learning Python. My code below threw an error. Please:
- First, DIAGNOSE the root cause in plain English (do not give me a fix yet).
- Then, give me a corrected version.
- Finally, suggest one tiny test I can run to confirm the fix worked.
What I expected:
[describe].The code:
[paste]The error:
[paste full traceback]
The "diagnose first" instruction is critical. It stops the AI from guessing at a fix that masks the real bug.
A Worked Example
Suppose you ran this code:
import pandas as pd
df = pd.read_csv("students.csv")
average = df["score"].mean()
print(f"Class average: {average}")
You got this error:
KeyError: 'score'
A bad prompt: "why is this broken?" — the AI guesses, often wrong.
A good prompt:
Diagnose this
KeyError: 'score'first. Here is the code I ran (paste). Here is whatdf.columnsreturns:Index(['name', 'Score', 'grade'], dtype='object'). What I expected: read a CSV and compute the average of the score column.
The AI now sees that the column is named Score (capital S), not score. The fix is df["Score"].mean(). The diagnosis taught you that pandas column names are case-sensitive — a fact that will save you hours over your career.
The Five Errors You Will See Most
Memorize these. AI will help, but recognizing them on sight makes you faster.
SyntaxError — a typo. Often a missing colon, unmatched bracket, or stray comma. Look at the line before the one Python flags; the actual problem is often there.
NameError: name 'X' is not defined — you used a variable that does not exist. Common cause: typo (prnit instead of print), or you forgot to assign the variable, or you imported a library but called it by the wrong name (pandas.read_csv when you wrote import pandas as pd).
TypeError: ... — you tried to do something with the wrong type. Adding a string and an integer ("3" + 5), calling a function on something that does not support it. Run type(your_variable) to confirm what you are working with.
KeyError: 'X' — you asked for a dictionary key or pandas column that does not exist. Run df.columns or dict.keys() to see what is actually there.
IndentationError — your indentation is inconsistent. Pick four spaces, stick with it, and let your editor handle it.
When AI's Fix Is Wrong
AI sometimes gives you a fix that runs but does not actually solve the problem. Watch for these patterns:
- The "fix" silently swallows the error with
try/except: pass. This hides the bug rather than fixing it. - The fix changes a column name to something different, "to avoid the error." That is renaming the symptom, not curing the disease.
- The AI rewrites the whole function instead of changing the broken line. Read carefully — the rewrite may compute something different from what you wanted.
When you suspect this, push back:
Your fix changed
scoretototal. Does that compute the same thing my original code was supposed to compute? Walk me through both.
AI is happy to debate itself when challenged. The student who asks "are you sure?" finds bugs the student who copy-pastes does not.
The "Verify" Step
The third step in DIAGNOSE → FIX → VERIFY is the one most learners skip. After running the corrected code, confirm the answer matches a known value.
If you fixed an average computation, compute the average a different way as a check:
# original way (now fixed)
average = df["Score"].mean()
# manual sanity check
average_check = sum(df["Score"]) / len(df["Score"])
assert abs(average - average_check) < 0.001
If both give the same number, the fix is solid. If they disagree, dig deeper — pandas .mean() skips missing values, while sum() does not, and the difference reveals data quality issues.
Debugging Without an Error Message
Sometimes code runs but produces wrong output. This is harder. Use this prompt:
My code runs without errors but the output is wrong. Here is the code, the actual output, and what I expected. Please diagnose three possible causes, ranked from most likely to least likely, before suggesting any fix.
Code:
[paste]Actual output:[paste]Expected output:[paste]
Asking for ranked hypotheses forces the AI to think about possibilities rather than jumping to the first plausible answer.
A Common Pitfall: Modifying While Iterating
Here is a real beginner trap that AI catches well:
scores = [70, 85, 90, 50, 60]
for s in scores:
if s < 70:
scores.remove(s)
print(scores) # [70, 85, 90, 60] — 60 was missed!
Modifying a list while looping over it skips elements. The fix is to build a new list:
passing = [s for s in scores if s >= 70]
This is the kind of bug AI explains in a sentence: "you are mutating the list you are iterating over, which shifts indices and causes the loop to skip elements."
Key Takeaways
- Always share three things: full error, full code, and what you expected
- Use DIAGNOSE → FIX → VERIFY to avoid masking bugs with band-aid fixes
- Memorize the five common errors so you recognize them on sight
- Push back when AI's fix changes the meaning of your code
- Verify the answer against a manual computation whenever possible

