Sub topic 6
Where AI Answers Go Wrong
This chapter assumes you can write functions, conditionals and loops in Python, run a script from a terminal or editor, and have used a chat assistant or code completion at least a few times. Earlier chapters covered how to ask for hints and explanations. This one covers why you can't trust the answers without checking them, and which kinds of mistakes to expect.
Why fluent answers still fail
A language model produces text that is likely to follow your prompt. It does not run the code, look up the library's current documentation, or know what your project contains. Most of the time, likely text is also correct text. When it isn't, the answer reads just as smoothly as a correct one.
This matters for learning. If you rely on the tone of an answer ("Here's the corrected version"), you stop building the judgment you need to tell good code from bad. The skill to practice is checking, and the failure modes below tell you where to look.
Common failure modes
| Failure mode | What it looks like | Typical symptom |
|---|---|---|
| Invented API | A method, function or parameter that does not exist | `AttributeError`, `TypeError`, or an import error |
| Outdated advice | Code written for an older library version | Deprecation warnings, or a crash after an upgrade |
| Subtle logic error | Code that works on the example but not on edge cases | Wrong output for empty, single-item or boundary input |
| Wrong problem | A correct solution to a question you did not ask | Code runs but does not do what your task needs |
| Missing context | Names or structures that do not match your code | Fixes that clash with your existing files |
| Unsafe code | Building SQL from strings, hardcoded secrets, disabled checks | Works in a demo, fails a security review |
| Agreeing with your mistake | Accepting a wrong assumption in your prompt | Your misunderstanding comes back with more confidence |
The sections below take these in turn.
Invented APIs
The model has seen many libraries and may blend them. It can produce a method that sounds right because similar methods exist elsewhere. Here is a typical example. JavaScript arrays have flat(), and some Python libraries have flatten helpers, so a model might write flatten() on a Python list.
numbers = [[1, 2], [3], [4, 5]]
try:
flat = numbers.flatten()
except AttributeError as error:
print("Error:", error)
flat = [value for row in numbers for value in row]
print(flat)Running this prints Error: 'list' object has no attribute 'flatten', then [1, 2, 3, 4, 5]. The error is the easy case, because it fails loudly and you find out immediately.
Invented APIs are harder to catch when they sit inside a library you don't know yet. Check the official documentation for any function you haven't seen before. In a Python session, help(name) and dir(object) show what exists in the version you have installed.
Outdated or mismatched versions
A model learns from text written over many years. It may suggest a function that was removed, a configuration style that has changed, or an install command for an older tool. Version problems are common in fast-moving areas such as web frameworks and data libraries.
When something fails oddly, check three things:
- The version of the language or library you actually run (
python --version,pip show package-name). - The version the answer seems to assume. Look at the import style and the function names.
- The changelog or migration guide in the official documentation.
If you tell the assistant your versions in the prompt, answers improve, but that does not remove the need to check.
Plausible code with subtle logic errors
The most dangerous failure is code that runs without errors and gives a wrong result. Here is a function of the kind an assistant might write for splitting a list into chunks.
def chunk_buggy(items, size):
"""Split items into lists of at most `size` elements."""
return [items[i:i + size] for i in range(0, len(items) - size, size)]
def chunk(items, size):
"""Split items into lists of at most `size` elements."""
if size < 1:
raise ValueError("size must be at least 1")
return [items[i:i + size] for i in range(0, len(items), size)]
print(chunk_buggy([1, 2, 3, 4, 5], 2))
print(chunk([1, 2, 3, 4, 5], 2))
assert chunk([1, 2, 3, 4, 5, 6], 2) == [[1, 2], [3, 4], [5, 6]]
assert chunk([1, 2, 3, 4, 5], 2) == [[1, 2], [3, 4], [5]]
assert chunk([], 3) == []
assert chunk([1], 5) == [[1]]The first call prints [[1, 2], [3, 4]], which silently drops the 5. The second prints [[1, 2], [3, 4], [5]]. The bug is the range stop value, len(items) - size. It stops one step too early, so the last chunk disappears. A quick glance at the buggy version looks fine, and a test with only a short list might even pass by accident.
The pattern to remember: an off-by-one boundary, a missing empty-input case, or a wrong comparison operator hides behind code that looks tidy. The tests you write in the verification chapter are the main defense. For now, learn to ask of any generated loop: what happens at the first item, the last item, and with nothing at all?
Solving the wrong problem
Assistants try to be helpful with the words you gave them. If your prompt is vague, they fill the gaps with guesses. Ask for "a function to clean this data" and you may get one that lowercases everything, drops duplicates and strips punctuation. Your task may have needed only one of those.
Signs of this failure:
- The answer adds features you did not ask for.
- The answer ignores a constraint you stated, such as "no external libraries" or "keep the existing function signature".
- The code is much longer than the task seems to need.
Before accepting code, restate the task in one sentence and compare it with what the code does. If you cannot describe what each part is for, that is a reason to ask about it, not to keep it.
Missing context
The assistant only sees what you paste. It does not know your other files, your naming, your data format or your earlier decisions. It may invent a variable that does not exist in your project, assume a column name, or fix an error by changing something that other code depends on.
Give it the smallest piece of context that lets it reason correctly: the relevant function, the exact error message, a sample of the input, and the version of the language. Avoid pasting your whole project, which hides the important part and may expose secrets. Never paste passwords, API keys or private data.
Unsafe defaults
Generated code often optimizes for being short and demonstrable. That can mean string-built SQL queries, eval on user input, disabled certificate checks, or credentials written directly in the source. These examples work, which is why they are risky.
Agreeing with a wrong premise
Assistants tend to go along with the framing of a question. If you write "Since Python passes everything by value, why does my list change?", a weak answer may work inside your false premise instead of correcting it. In Python, names refer to objects, and a function that receives a list can modify that same list.
To reduce this, ask neutral questions ("What happens to the list when I pass it to this function?") rather than questions that embed your belief. You can also ask directly: "Is there any assumption in my question that is wrong?"
Confidence is not evidence
An assistant sounds equally sure when it is right and when it is wrong. Phrases such as "this will work" or "the issue is" carry no information about reliability. Asking "Are you sure?" often produces either a reversal or a longer defense of the same answer. Neither is a check.
Reliable evidence comes from outside the model:
- Running the code on inputs you chose.
- Reading official documentation.
- Tests that you wrote before looking at the answer.
- Comparing the result with what you predicted.
A checking routine
Use the same short routine every time you receive generated code. It takes a couple of minutes and builds the habit you need before the next chapter's closer reading.
The last step connects to learning: if you cannot explain accepted code in your own words, you have not finished with it.
Using failures as practice
Wrong answers are not only a risk. Finding the flaw is a good exercise in reading code and forming hypotheses. When you catch a mistake, write down what kind it was, using the categories in the table. After a few weeks you will see which ones you tend to miss, and you can focus your checking on those.
Exercise
An assistant gives you def average(values): return sum(values) / len(values). It runs correctly on [2, 4, 6]. Name one input where it fails, say which failure mode from this chapter it illustrates, and describe how you would fix or guard it.
Show answer
It fails on an empty list, because len(values) is 0 and Python raises ZeroDivisionError. This is a subtle logic error: the code is fine on a typical example but misses an edge case. A fix is to decide what an empty input should mean and make it explicit, for example if not values: raise ValueError("average() requires at least one value"). Then add a test that checks this behavior along with tests for one item and several items.
Exercise
You ask an assistant how to read a file in a library you are using, and it suggests reader.read_all(path, strict=True). The code fails with TypeError: unexpected keyword argument 'strict'. List three checks you should run before asking the assistant to try again.
Show answer
First, check the official documentation for the function signature to see whether strict exists at all. Second, check which library version you have installed (for example with pip show) and compare it with the version in the documentation. Third, use help(reader.read_all) in a Python session to see the real parameters. Then, when you ask again, include the exact error, your version and the documented signature.