Sub topic 10
Explaining the Code Back in Your Own Words
This chapter assumes you can write functions, loops and conditionals in Python, run a script and a simple test, and have used a chat-based AI assistant. Earlier chapters covered reading generated code critically and checking it with tests. This chapter covers the next step: explaining code in your own words, which shows whether you understood it.
Why explaining is a test of understanding
When you read AI-generated code and it looks right, you feel that you understand it. That feeling is often wrong. Psychologists call it the illusion of fluency. Text that reads smoothly feels familiar, and familiarity is easy to mistake for knowledge.
Explaining the code in your own words tests the feeling. If you can't say what a line does, why it is there, or what happens on unusual input, you have found a gap while it is cheap to fix. Researchers call this technique self-explanation. Learners who explain worked examples to themselves tend to do better on later problems than learners who only reread them.
Explaining back also connects to two earlier ideas:
- It is retrieval practice. You pull the logic out of your memory instead of rereading it.
- It is a check on your attempt-first work. If the AI's version differs from yours, you can only compare the two if you understand both.
Three levels of explanation
A good explanation works at several levels. Most weak explanations stay on the first one.
| Level | Question it answers | Example for a function that removes duplicates |
|---|---|---|
| Line level | What does each statement do? | "`seen.add(item)` puts the item into a set." |
| Behavior level | What goes in, what comes out, and what happens on edge cases? | "It returns a new list with the first occurrence of each item, in the original order. An empty list gives an empty list." |
| Intent and design level | Why was it written this way, and what else could have been done? | "A set makes the membership check fast. The separate list keeps the order. Using only `set(items)` would lose the order." |
Aim for all three. If you can only give the line-level version, you have paraphrased the code, not explained it.
A worked example
Suppose an AI gives you this function for removing duplicates while keeping order:
def unique_in_order(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(unique_in_order([3, 1, 3, 2, 1]))Before running it, write your explanation down, closed-book if you can. Here is a weak first attempt:
It loops through the items and adds them to a set and a list if they are not in the set, then returns the list.This is accurate but only restates the code. It never says why there are two containers, what the output is, or what could go wrong. Here is a stronger version:
Input: any list of hashable values. Output: a new list with the first occurrence of each value, in the original order.
The set `seen` answers "have I met this value before?" quickly. The list `result` stores the answer in order, because a set does not keep order for us to rely on.
Trace for [3, 1, 3, 2, 1]: 3 is new, so result = [3]. 1 is new, so result = [3, 1]. 3 is already seen, so skip. 2 is new, so result = [3, 1, 2]. 1 is already seen, so skip. Final: [3, 1, 2].
Edge cases: an empty list returns []. A list of lists would fail, because lists are not hashable and cannot go into a set.The strong version names the input and output, explains why each data structure exists, includes a trace, and makes a claim about an edge case. Claims like that last one can be tested, so check it:
def unique_in_order(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
assert unique_in_order([3, 1, 3, 2, 1]) == [3, 1, 2]
assert unique_in_order([]) == []
try:
unique_in_order([[1], [2], [1]])
except TypeError as error:
print("TypeError, as predicted:", error)
else:
raise AssertionError("expected a TypeError for unhashable items")If your prediction about the list-of-lists case had been wrong, that would be useful. You would have found something your mental model missed, and you would fix the explanation, not just the code.
Techniques for explaining back
Trace with concrete values
Pick a small input and write down the value of each variable after each step. Tracing is the most reliable way to expose a gap, because you can't hide behind general phrases like "it processes the list". Choose inputs that exercise different branches: a duplicate, a single element, an empty input.
Predict, then run
Write your expected output, run the code, and compare. A match is weak evidence of understanding. A mismatch is strong evidence of a gap, and it points to the exact place to investigate. Keep your prediction in a comment or a notes file so you can't quietly revise it after seeing the result.
Explain without looking
Read the code once, hide it, and write the explanation from memory. Then reopen the code and mark what you missed or got wrong. Missing details show what you did not encode. Wrong details show a misconception, which matters more.
Rebuild a piece from your explanation
Close the AI's answer and write a version of the function from your own explanation. If you can't, the explanation was too vague to be useful. If you can, run your version against the same tests as the original.
Use one-sentence summaries
Write a single sentence for each block of the code, such as "this loop builds the ordered result". If a sentence needs the word "stuff" or "things", you haven't pinned down what is happening.
Using the AI as a listener
You can ask the AI to check your explanation instead of giving its own. This keeps the thinking on your side. A prompt like this works well:
Here is a function and my explanation of it. Do not rewrite the code or give me a full explanation.
Code:
<paste the code>
My explanation:
<paste your explanation>
Tell me, in this order:
1. Anything in my explanation that is factually wrong.
2. One thing I left out that matters (for example an edge case).
3. One question that would test whether I really understand the design choice.Answer the question yourself before asking for more. Treat the AI's feedback as input to verify, not as a verdict. Chapter limits on AI output apply here too: it can approve a flawed explanation or flag a correct one. When the AI and your explanation disagree, settle it by running the code, not by trusting either side.
The loop below shows the whole process.
Common errors
- Parroting. You repeat the code in English ("it loops, then checks, then appends"). Fix: add a "because" to each step. If you can't, you don't know the reason yet.
- Explaining only the happy path. You describe normal input and ignore empty, single-item, duplicate or invalid input. Fix: always write at least two edge cases and say what happens.
- Vague words. "It handles the data" or "it sorts things out" hides what happens. Fix: replace each vague word with a specific operation or value.
- Explaining what you wished the code did. You describe the intended behavior, not the actual one. A trace with real values catches this.
- Skipping the unfamiliar part. You explain the easy lines and gloss over a library call or an operator you don't know. Fix: look it up in the official documentation, then write what it returns for one concrete input.
- Treating the AI's praise as proof. "Your explanation is correct" from an AI is not a test. Run something.
Edge cases in the practice itself
Explaining back has limits, and it helps to know them.
- A good explanation of wrong code is still wrong. Understanding what the code does doesn't show that it is correct. Pair explanation with tests you write yourself.
- Fluent explanations can be memorized. If you memorize the AI's wording, you are back to the illusion of fluency. Use your own words, a different input from the one in the example, and a variation ("what if the order didn't matter?").
- Long code needs chunking. Don't try to explain 200 lines at once. Explain one function at a time, then explain how the functions connect.
- Some code resists explanation. If you truly can't explain a piece after tracing it, that is a signal to ask the AI for a hint, or to rewrite the piece more simply. Code you can't explain is a maintenance risk even if it passes tests.
- Time cost is real. Explaining everything is slow. Spend the effort on code you plan to keep, on new concepts, and on anything touching data or security. For a throwaway one-liner, a quick prediction may be enough.
A practical routine
- Read the generated code once.
- Write a three-level explanation (lines, behavior, design) without looking.
- Trace one normal input and one edge case.
- Run the code and compare with your trace.
- Ask the AI to find errors in your explanation, not to replace it.
- Save the final explanation as a comment or note. You can reread it later as a check on whether you still remember it.
Exercise
A learner explains unique_in_order as "it goes through the list and keeps the new items." List two things that explanation is missing and say which level of explanation each belongs to.
Show answer
Any two of these: (1) why a set is used next to the list, which is the design level; (2) that the output keeps the original order and only the first occurrence of each value, which is the behavior level; (3) what happens on edge cases such as an empty list or unhashable items like lists, which is the behavior level; (4) what each statement does, such as seen.add(item), which is the line level.
Exercise
Write a short function count_vowels(text) that returns the number of vowels in a string, ignoring case. Before running print(count_vowels("Learning with AI")), write your predicted result and a trace of which letters are counted. Then run it. What do you do if your prediction and the output differ?
Show answer
The vowels in "Learning with AI" are e, a, i, i, A, I, so the expected result is 6. A correct function is def count_vowels(text): return sum(1 for ch in text.lower() if ch in "aeiou"). If the output differs from your prediction, do not just change the prediction. Re-trace the input letter by letter, find the step where your mental model diverged from the code (for example, forgetting that lower() makes capital vowels count), and rewrite your explanation.
Exercise
You paste your explanation of a function into an AI, and it says the explanation is correct. Your explanation claims that the function raises a ValueError on an empty list. What should you do before trusting either the AI or yourself?
Show answer
Run the function with an empty list and see what happens. The AI's agreement is not evidence, and your claim about behavior can be tested directly. If the function does not raise ValueError, fix your explanation and record what actually happens.