SyntaxPilot
Courses/Vibe Coding/Lesson 7
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Vibe Coding · Lesson 7 of 40

Reading AI-generated code

reading code top-downfunctionsvariablesimportsasking the AI to explain a filecomments vs docsspotting dead code and duplicated logicthe 'never ship code you cannot explain' rule

Vibe Coding: build real apps with AI · Episode 7. Every agent run below is real: Claude Code 2.1.319 (model claude-sonnet-5-5) in print mode (claude -p) with --output-format stream-json, on 6-7 November 2026, in /home/ravi/projects/settle, the Git project from Episode 6. Replies are quoted exactly, shortened where marked .... All program output is real (Python 3.13). Agents don't answer identically every run; the lessons don't change.

The problem: code that runs, then breaks

Ravi's flat app (settle.py) tells everyone who pays whom. The flat wants a report: what each person paid, their share, and their balance. Ravi asks an agent:

ravi@laptop:~/projects/settle$ claude -p "Add a report to this project: for each person, show how much they paid, their share of the costs, and their balance (paid minus share). Put it in a new file report.py with a small example at the bottom." --allowedTools Read Write Edit "Bash(python3 report.py)"
1 Bash   ls -la && git log --oneline | head -5 && wc -l *.py
2 Read   settle.py
3 Read   test_settle.py
4 Write  report.py          → File created successfully
5 Bash   python3 report.py && python3 test_settle.py   → requires approval
6 Bash   python3 report.py  → (the table below)
7 Reply: "I added report.py ... I didn't change settle.py, so the
   existing tests shouldn't be affected. ...
   - Duplicated logic: the split logic is copied from settle.py
     rather than shared. If you'd rather have one source of truth,
     I can pull the split into a helper that both files use."
ravi@laptop:~/projects/settle$ python3 report.py
Name        Paid       Share     Balance
Ravi        1800         800        1000
Neha         300         500        -200
Sam            0         800        -800

It runs and the numbers are right, so Ravi commits it without reading it. A week later, a phone adds a space after a name ("Ravi "). Ravi asks the agent to fix settle.py:

ravi@laptop:~/projects/settle$ claude -p "People type names on their phones and sometimes add a space, like \"Ravi \". In settle.py, ignore spaces around names so \"Ravi \" counts as \"Ravi\". Then run the tests with: python3 test_settle.py" --allowedTools Read Edit "Bash(python3 test_settle.py)"
1 Read   settle.py
2 Edit   settle.py   (adds .strip() in three places)
3 Bash   python3 test_settle.py   → All tests passed
4 Reply: "settle.py now ignores spaces around names, so "Ravi " counts
   as "Ravi". python3 test_settle.py prints "All tests passed". ...
   I didn't add a test for a padded name like "Ravi "."

Tests pass. Then he runs both functions with "Ravi ":

['Sam pays Ravi Rs 500', 'Neha pays Ravi Rs 200']
Traceback (most recent call last):
  File "<string>", line 5, in <module>
  File "/home/ravi/projects/settle/report.py", line 22, in report
    raise ValueError(f"Unknown name: {name}")
ValueError: Unknown name: Ravi 

settle() works; report() crashes. Why? report.py had its own copy of settle's loop, and only one copy got the fix. The agent even said so on day one, in the last lines of its reply: "Duplicated logic: the split logic is copied from settle.py rather than shared." Running is not understanding.

Real-life example: a rent agreement. You sign it because it looks official, move in, everything works, and then the tap breaks and clause 14 says "tenant pays all repairs". It was there all along. Reading is cheap; surprises aren't.

Reading a file top-down (like a recipe)

A recipe A code file What you look for
Ingredients list imports at the top what the file borrows from other files
Step names def lines the table of contents: which functions exist
"Serve with chutney" the bottom block what actually runs
Each step, carefully each function inputs → steps → what it returns

report.py as the agent wrote it (39 lines):

def _rs(paise):
    """Format paise like settle.py does: 500 -> '5', 16667 -> '166.67', negatives keep the sign."""
    sign = "-" if paise < 0 else ""
    rs, ps = divmod(abs(paise), 100)
    return f"{sign}{rs}.{ps:02d}" if ps else f"{sign}{rs}"


def report(people, expenses):
    """Per-person table of what they paid, their share of the costs, and balance (paid - share).

    Takes the same arguments as settle(), and splits each expense the same way
    (in paise, with leftover paise going to the first people in the list),
    so balances here match what settle() asks people to pay.
    """
    paid = {p: 0 for p in people}
    share = {p: 0 for p in people}
    for payer, amt, *rest in expenses:
        paise = round(amt * 100)
        parts = rest[0] if rest else people
        for name in [payer, *parts]:
            if name not in paid:
                raise ValueError(f"Unknown name: {name}")
        base, extra = divmod(paise, len(parts))
        paid[payer] += paise
        for k, p in enumerate(parts):
            share[p] += base + (k < extra)

    width = max(len(p) for p in people + ["Name"])
    lines = [f"{'Name':<{width}}  {'Paid':>10}  {'Share':>10}  {'Balance':>10}"]
    for p in people:
        lines.append(
            f"{p:<{width}}  {_rs(paid[p]):>10}  {_rs(share[p]):>10}  {_rs(paid[p] - share[p]):>10}"
        )
    return "\n".join(lines)


if __name__ == "__main__":
    flat = ["Ravi", "Neha", "Sam"]
    print(report(flat, [("Ravi", 1200), ("Neha", 300), ("Ravi", 600, ["Ravi", "Sam"])]))
  1. Imports: none. It borrows nothing, so it can't be using settle.py's logic. A clue.
  2. def lines: _rs (line 1) and report (line 8). Two functions.
  3. The bottom: if __name__ == "__main__": means "run this only when the file is run directly" (python3 report.py), not when another file imports it. It makes a variable flat and prints one report.
  4. The details: paid and share are dictionaries; the loop (lines 17-26) is the same loop as in settle.py. Line 22 is the line that crashed.

Variables

A variable is a name for a value, like a label on a jar: flat = ["Ravi", "Neha", "Sam"]. Use the label and you get what's inside. Variables made inside a function (sign, rs, ps) exist only while that function runs.

Functions, parameters and return values

A function is a named, reusable block of steps. Parameters are its inputs (the names in brackets), and return is what it hands back to whoever called it.

def _rs(paise):
    """Format paise as rupees: 16667 -> '166.67'."""
    sign = "-" if paise < 0 else ""
    rs, ps = divmod(abs(paise), 100)
    return f"{sign}{rs}.{ps:02d}" if ps else f"{sign}{rs}"

print(_rs(16667))
print(_rs(500))
print(_rs(-20000))
print(_rs(5))
print(_rs.__doc__)

Output:

166.67
5
-200
0.05
Format paise as rupees: 16667 -> '166.67'.

One function, called four times, four answers. divmod(a, b) gives the whole part and the remainder at once: divmod(16667, 100) is (166, 67).

Asking the AI to explain a file

Give it only the Read tool so it can't change anything:

ravi@laptop:~/projects/settle$ claude -p "I'm a beginner. Explain report.py to me top to bottom, in plain words. Don't change any files." --tools Read
report.py prints a small table showing, for each person, how much they
paid, how much they owed, and the difference. It has two functions and
a demo at the bottom.
_rs(paise): This is a helper. The leading underscore is a convention
meaning "for internal use". ... divmod(abs(paise), 100) gives the whole
rupees and the leftover paise in one step. ...
if __name__ == "__main__": means this part runs only when you run the
file directly. ...
By my hand calculation (I haven't run it), the result is: ...
Things to know:
- people must be a list, because line 28 does people + ["Name"].
- If an expense has an empty sharer list, line 23 divides by zero.
- The docstring says this matches a settle() function, which I haven't
  looked at. The two files need to stay in sync for the balances to agree.

A good explanation, in the same top-down order. Note "By my hand calculation (I haven't run it)": an explanation is a claim. Check one: an empty sharer list.

def report(people, expenses):
    paid = {p: 0 for p in people}
    share = {p: 0 for p in people}
    for payer, amt, *rest in expenses:
        paise = round(amt * 100)
        parts = rest[0] if rest else people
        for name in [payer, *parts]:
            if name not in paid:
                raise ValueError(f"Unknown name: {name}")
        base, extra = divmod(paise, len(parts))
        paid[payer] += paise
        for k, p in enumerate(parts):
            share[p] += base + (k < extra)
    return paid, share

print(report(["Ravi", "Neha"], [("Ravi", 300)]))
print(report(["Ravi", "Neha"], [("Ravi", 300, [])]))
$ python3 zero.py
({'Ravi': 30000, 'Neha': 0}, {'Ravi': 15000, 'Neha': 15000})
Traceback (most recent call last):
  File "zero.py", line 17, in <module>
    print(report(["Ravi", "Neha"], [("Ravi", 300, [])]))
          ~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "zero.py", line 10, in report
    base, extra = divmod(paise, len(parts))
                  ~~~~~~^^^^^^^^^^^^^^^^^^^
ZeroDivisionError: integer division or modulo by zero

The AI was right, and now we know it. This is a latent bug: a bug waiting for the right input.

Duplicated logic

The same rule written in two places. Fix one copy and the other is now wrong.

settle.py after the fix report.py's copy
payer = payer.strip() (missing)
parts = [p.strip() for p in rest[0]] if rest else people parts = rest[0] if rest else people
"Ravi " → "Ravi" ✓ "Ravi " → ValueError ✗

Real-life example: the Wi-Fi password on two notes, one on the fridge and one in the hall. You change the password and update the fridge note; a guest reads the hall note and it doesn't work. The fix: one note, one place.

The fix: one shared function, and imports

ravi@laptop:~/projects/settle$ claude -p "report.py copies the split logic from settle.py, and now they disagree: settle() accepts \"Ravi \" but report() says Unknown name. Pull the shared logic into one function in settle.py that both use. Keep behaviour the same. Check with: python3 test_settle.py and python3 report.py" --allowedTools Read Edit "Bash(python3 test_settle.py)" "Bash(python3 report.py)"
1 Read   settle.py, report.py
2 Edit   settle.py   (new function split_expenses; settle() calls it)
3 Edit   report.py   (its copy of the loop → one call)
4 Edit   report.py   (adds: from settle import split_expenses)
5 Bash   python3 test_settle.py && python3 report.py → All tests passed + the table
6 Reply: "... I didn't run report() with a padded name like "Ravi ".
   That check needed a separate command that wasn't approved, so the
   padded-name fix is untested."
diff --git a/report.py b/report.py
+from settle import split_expenses
+
 def _rs(paise):
...
-    paid = {p: 0 for p in people}
-    share = {p: 0 for p in people}
-    for payer, amt, *rest in expenses:
-        paise = round(amt * 100)
-        ... (8 more lines removed)
+    people, paid, share = split_expenses(people, expenses)

diff --git a/settle.py b/settle.py
+def split_expenses(people, expenses):
+    """Return (people, paid, share): stripped names and per-person paise paid / owed."""
...
+    return people, paid, share
+
+def settle(people, expenses):
+    people, paid, share = split_expenses(people, expenses)
+    bal = {p: paid[p] - share[p] for p in people}

from settle import split_expenses is an import: borrow the function split_expenses from the file settle.py. Now there is one copy of the rule. The agent said the padded-name case was untested, so Ravi tested it:

ravi@laptop:~/projects/settle$ python3 -c 'from report import report; print(report(["Ravi","Neha","Sam"], [("Ravi ",1200), ("Neha",300)]))'
Name        Paid       Share     Balance
Ravi        1200         500         700
Neha         300         500        -200
Sam            0         500        -500
ravi@laptop:~/projects/settle$ python3 test_settle.py
All tests passed

The final files:

# settle.py
def split_expenses(people, expenses):
    """Return (people, paid, share): stripped names and per-person paise paid / owed.

    Names are stripped of whitespace; leftover paise go to the first people in each split.
    """
    people = [p.strip() for p in people]
    paid = {p: 0 for p in people}
    share = {p: 0 for p in people}
    for payer, amt, *rest in expenses:
        payer = payer.strip()
        paise = round(amt * 100)
        parts = [p.strip() for p in rest[0]] if rest else people
        for name in [payer, *parts]:
            if name not in paid:
                raise ValueError(f"Unknown name: {name}")
        base, extra = divmod(paise, len(parts))
        paid[payer] += paise
        for k, p in enumerate(parts):
            share[p] += base + (k < extra)
    return people, paid, share


def settle(people, expenses):
    people, paid, share = split_expenses(people, expenses)
    bal = {p: paid[p] - share[p] for p in people}
    debt = sorted([[-b, p] for p, b in bal.items() if b < 0], reverse=True)
    cred = sorted([[b, p] for p, b in bal.items() if b > 0], reverse=True)
    out, i, j = [], 0, 0
    while i < len(debt) and j < len(cred):
        x = min(debt[i][0], cred[j][0])
        rs, ps = divmod(x, 100)
        amount = f"{rs}.{ps:02d}" if ps else f"{rs}"
        out.append(f"{debt[i][1]} pays {cred[j][1]} Rs {amount}")
        debt[i][0] -= x
        cred[j][0] -= x
        i += debt[i][0] == 0
        j += cred[j][0] == 0
    return out
# report.py
from settle import split_expenses


def _rs(paise):
    """Format paise like settle.py does: 500 -> '5', 16667 -> '166.67', negatives keep the sign."""
    sign = "-" if paise < 0 else ""
    rs, ps = divmod(abs(paise), 100)
    return f"{sign}{rs}.{ps:02d}" if ps else f"{sign}{rs}"


def report(people, expenses):
    """Per-person table of what they paid, their share of the costs, and balance (paid - share).

    Takes the same arguments as settle(), and splits each expense the same way
    (in paise, with leftover paise going to the first people in the list),
    so balances here match what settle() asks people to pay.
    """
    people, paid, share = split_expenses(people, expenses)

    width = max(len(p) for p in people + ["Name"])
    lines = [f"{'Name':<{width}}  {'Paid':>10}  {'Share':>10}  {'Balance':>10}"]
    for p in people:
        lines.append(
            f"{p:<{width}}  {_rs(paid[p]):>10}  {_rs(share[p]):>10}  {_rs(paid[p] - share[p]):>10}"
        )
    return "\n".join(lines)


if __name__ == "__main__":
    flat = ["Ravi", "Neha", "Sam"]
    print(report(flat, [("Ravi", 1200), ("Neha", 300), ("Ravi", 600, ["Ravi", "Sam"])]))

A review for duplicates and dead code

ravi@laptop:~/projects/settle$ claude -p "Review this project for dead code (code that never runs or is never used) and duplicated logic. List what you find with file and line numbers. Don't change any files." --tools Read Glob Grep
"I found no real dead code in this project. There is one clear case of
duplicated logic ...
1. Paise-to-rupees formatting is written twice.
   - settle.py:31-32 does divmod(x, 100) and then
     f"{rs}.{ps:02d}" if ps else f"{rs}".
   - report.py:4-8 (_rs) does the same thing and also handles negatives.
   ... A shared helper in settle.py that report.py imports would fix this.
The expense-splitting logic is not duplicated. report.py:18 reuses
split_expenses from settle.py ...
- Empty split list: an expense with an empty participants list ([])
  would hit divmod(paise, 0) at settle.py:16 and raise ZeroDivisionError.
  This is a latent bug, not dead code."

Ravi checked the line numbers: correct. Two to-dos for the next one-change prompts: one shared money formatter, and a clear error for an empty sharer list.

Dead code

Dead code is code that never runs or is never used, like a light switch wired to nothing. It doesn't crash, so it hides; it costs attention, and AI tools may copy it. A made-up practice file:

import math


def _rs(paise):
    rs, ps = divmod(paise, 100)
    return f"{rs}.{ps:02d}" if ps else f"{rs}"
    print("formatted", rs)


def _rs_old(paise):
    return str(paise / 100)


print(_rs(16667))
$ python3 old_report.py
166.67
$ pip install vulture && python3 -m vulture old_report.py
old_report.py:1: unused import 'math' (90% confidence)
old_report.py:7: unreachable code after 'return' (100% confidence)
old_report.py:10: unused function '_rs_old' (60% confidence)

Three kinds: an unused import, unreachable code after return, and an unused function. vulture (2.16) only guesses ("60% confidence"); you decide. On Ravi's real project it prints nothing.

Comments vs docs

Comment Docstring
Looks like # paise, not rupees: avoids 0.1 + 0.2 errors """Format paise as rupees: 16667 -> '166.67'."""
For people reading the code people using the function
Python ignores it keeps it (_rs.__doc__, editors show it on hover)
Should say why what goes in and what comes out

Both can go out of date. When you read AI code, check that the notes still match the code.

The rule: never ship code you can't explain

Before you commit, answer five questions:

  1. What goes in? (parameters)
  2. What comes out? (return value)
  3. What happens on weird input? ("Ravi ", [], a typo)
  4. Is this rule written anywhere else? (duplicates)
  5. Does anything here never run? (dead code)

Can't answer? Don't ship. Ask the AI to explain, then check its claims by running the code.

Common mistakes (real)

What happened What you see Why Fix
committed report.py without reading it ValueError: Unknown name: Ravi it had its own copy of settle's loop read top-down before you commit
skipped the last lines of the reply "the split logic is copied ... rather than shared" the warning was there on day one read every reply to the end
asked to fix settle.py only settle ✓, report ✗ the agent changed only what we named ask: is this rule written anywhere else?
trusting "I haven't run it" ZeroDivisionError on an empty list an explanation is a claim run the code to check it

Mini project: read before you run

  1. Ask any AI for a 30-line Python script (for example: "a script that reads marks from a list and prints the class average and topper").
  2. Before running it, answer the five questions in writing.
  3. Ask the AI to explain it with a read-only prompt. Compare with your answers.
  4. Run it with one weird input (an empty list). Run python3 -m vulture on it.
What a good outcome looks like

You can say what each function takes and returns, you predicted the empty-list behaviour before running it (often ZeroDivisionError for an average), and you found at least one thing to change: a duplicated calculation, an unused import, or a comment that no longer matches the code.

Practice questions

  1. In what order should you read a new file?
Answer

Imports at the top, then the def lines (the table of contents), then the bottom block that actually runs, then each function's details.

  1. What does if __name__ == "__main__": mean?
Answer

Run this block only when the file is run directly (python3 report.py), not when another file imports it.

  1. Why did fixing settle.py not fix report.py?
Answer

report.py had its own copy of the same loop (duplicated logic); the fix went into one copy only.

  1. What does from settle import split_expenses do?
Answer

It borrows the function split_expenses from settle.py, so report.py uses the one shared copy instead of its own.

  1. Name three kinds of dead code.
Answer

An unused import, unreachable code after return, and a function that is never called.

  1. What's the difference between a comment and a docstring?
Answer

A # comment is a note for readers that Python ignores; a docstring (triple quotes under a def) documents how to use the function and Python keeps it (f.__doc__).

Quiz

def total(prices):
    s = sum(prices)
    return s
    print("done")

print(total([10, 20]))

Which line can never run? A) Line 2 · B) Line 3 · C) Line 4: print("done") · D) Line 6

Answer

C. return ends the function, so the print after it is unreachable (dead code). The program prints 30.

Interview questions

  1. How do you review code an AI wrote? Read it top-down (imports, function names, entry point, then details), ask the AI to explain anything unclear, verify its claims by running edge cases, and look for duplicated logic, dead code and stale comments before committing.
  2. Why is duplicated logic dangerous? A rule in two places means every change must be made twice; when one copy is missed the two parts of the app disagree, as settle and report did.
  3. What is dead code and how do you find it? Code that never runs or is never used; find it by reading, by coverage, or with tools like vulture, then remove it (Git keeps history).
  4. What is a docstring for? Documentation for users of a function: what it takes and returns. Comments explain why a piece of code is the way it is.

Glossary

Term Meaning (plain words) Example
Reading top-down imports → def lines → bottom block → details report.py
Variable a name for a value, like a label on a jar flat = ["Ravi", "Neha", "Sam"]
Function a named, reusable block of steps def report(people, expenses):
Parameter an input a function needs, named in brackets people, expenses
Return value what a function hands back return "\n".join(lines)
Call using a function by its name _rs(16667)
Dictionary a lookup table from keys to values {"Ravi": 0, "Neha": 0}
Loop repeat steps for each item for payer, amt, *rest in expenses:
divmod whole part and remainder in one step divmod(16667, 100) → (166, 67)
.strip() removes spaces around text "Ravi ".strip() → "Ravi"
__name__ == "__main__" true only when the file is run directly the demo block
Import borrow code from another file from settle import split_expenses
Duplicated logic the same rule written in two places the split loop in two files
Dead code code that never runs or is never used code after return
Unreachable code code that can never be reached print after return
Latent bug a bug waiting for the right input empty sharer list → ZeroDivisionError
Comment a # note for readers; Python ignores it # paise, not rupees
Docstring triple-quoted docs under a def; Python keeps it _rs.__doc__
ValueError Python error for a bad value Unknown name: Ravi
ZeroDivisionError dividing by zero divmod(300, 0)
vulture a free tool that finds dead Python code python3 -m vulture file.py
Refactor change how code is organised without changing what it does one shared split_expenses

Summary

  • Code that runs is not code you understand. Ravi's report ran fine and broke a week later.
  • Read top-down: imports, def lines, the bottom block, then each function's inputs, steps and return value.
  • Ask the AI to explain, then run to check its claims.
  • Hunt for duplicated logic (fix one copy, the other breaks: share one function and import it) and dead code (vulture helps; you decide).
  • Comments say why; docstrings document use; both must match the code.
  • Never ship code you can't explain.

Next episode: Your first 10-minute app: a tip calculator web page in HTML, CSS and JavaScript, with a real AI bug and the fix.