Vibe Coding: build real apps with AI · Episode 4. Every prompt below was really sent to Claude Code 2.1.318 in print mode (claude -p, follow-ups with claude -p --continue) on 6 November 2026, in an empty folder. Replies are quoted exactly (shortened only where marked ...). AI replies vary from run to run, so yours may differ; the lessons don't. Every program was run with Python 3.13 and the outputs shown are real.
The problem: month end at Ravi's flat
Ravi, Neha and Sam (the flatmates from Episode 1) share every expense equally. This month:
| Who | Paid | For |
|---|---|---|
| Ravi | ₹1,200 | groceries |
| Neha | ₹300 | wifi |
| Sam | ₹0 | – |
Total ₹1,500, so ₹500 each. Ravi is owed ₹700, Neha owes ₹200, Sam owes ₹500. Ravi wants a small function that answers "who pays whom?" every month.
Attempt 1: a one-line prompt
A prompt is the message you give the AI.
ravi@laptop:~/q$ claude -p "write code to split expenses"
claude -p = ask once and print the answer (Episode 3). The real reply (shortened):
```python
#!/usr/bin/env python3
"""Split shared expenses and compute the minimal set of settling payments.
Usage:
python split_expenses.py # runs the demo
python split_expenses.py file.json # JSON: [{"payer": "A", "amount": 30, "participants": ["A","B"]}, ...]
"""
import json
import sys
from collections import defaultdict
... (84 lines of code in all)
How it works - Amounts are converted to integer cents. ... I haven't run it. If you want, I can adapt it to a CLI, a web app, or a different language.
Ravi saved it as `split_expenses.py` and ran it:
ravi@laptop:~/q$ python3 split_expenses.py Balances: Alice +27.25 Bob -27.25 Carol +0.00
Settle up: Bob pays Alice 27.25
The code isn't wrong. It just isn't Ravi's: 84 lines, a JSON input file, made-up people (Alice, Bob, Carol), dollars and cents, extra features. Our rule from Episode 1: **never ship code you can't explain.**
<details markdown="1"><summary>The full 84-line program the AI wrote (for reference)</summary>
```python
#!/usr/bin/env python3
"""Split shared expenses and compute the minimal set of settling payments.
Usage:
python split_expenses.py # runs the demo
python split_expenses.py file.json # JSON: [{"payer": "A", "amount": 30, "participants": ["A","B"]}, ...]
# "participants" optional (defaults to everyone);
# optional "shares": {"A": 20, "B": 10} for unequal splits.
"""
import json
import sys
from collections import defaultdict
def balances(expenses):
"""Return {person: net balance in cents}. Positive = is owed, negative = owes."""
people = set()
for e in expenses:
people.add(e["payer"])
people.update(e.get("participants", []))
people.update(e.get("shares", {}))
bal = defaultdict(int)
for e in expenses:
total = round(e["amount"] * 100)
shares = e.get("shares")
if shares:
owed = {p: round(v * 100) for p, v in shares.items()}
if sum(owed.values()) != total:
raise ValueError(f"Shares don't add up to amount: {e}")
else:
parts = e.get("participants") or sorted(people)
base, extra = divmod(total, len(parts))
owed = {p: base + (1 if i < extra else 0) for i, p in enumerate(parts)}
bal[e["payer"]] += total
for p, v in owed.items():
bal[p] -= v
return dict(bal)
def settle(bal):
"""Greedy: biggest debtor pays biggest creditor. Returns [(from, to, cents)]."""
debtors = sorted(((p, -v) for p, v in bal.items() if v < 0), key=lambda x: -x[1])
creditors = sorted(((p, v) for p, v in bal.items() if v > 0), key=lambda x: -x[1])
payments, i, j = [], 0, 0
while i < len(debtors) and j < len(creditors):
d, owe = debtors[i]
c, due = creditors[j]
pay = min(owe, due)
payments.append((d, c, pay))
debtors[i] = (d, owe - pay)
creditors[j] = (c, due - pay)
if debtors[i][1] == 0:
i += 1
if creditors[j][1] == 0:
j += 1
return payments
def main():
if len(sys.argv) > 1:
with open(sys.argv[1]) as f:
expenses = json.load(f)
else:
expenses = [
{"payer": "Alice", "amount": 90, "participants": ["Alice", "Bob", "Carol"]},
{"payer": "Bob", "amount": 45.50, "participants": ["Alice", "Bob"]},
{"payer": "Carol", "amount": 60, "shares": {"Alice": 10, "Bob": 20, "Carol": 30}},
]
bal = balances(expenses)
print("Balances:")
for p, v in sorted(bal.items()):
print(f" {p:<10} {v / 100:+.2f}")
print("\nSettle up:")
payments = settle(bal)
if not payments:
print(" All square!")
for d, c, amt in payments:
print(f" {d} pays {c} {amt / 100:.2f}")
if __name__ == "__main__":
main()
Why it went wrong: every blank was filled with a guess
| What Ravi never said | What the AI guessed |
|---|---|
| Which language? | Python |
| What goes in? | a JSON file |
| What comes out? | balances + payments |
| Which money? | cents (dollars) |
| How big? | 84 lines, extra features |
An LLM (Episode 1) predicts a likely answer from your words. Every blank you leave is filled with a guess. A short prompt doesn't give you a short answer; it gives you more guesses.
The prompt recipe (ordering a birthday cake)
| At the bakery | In your prompt | Meaning |
|---|---|---|
| "A cake for Neha's birthday" | Goal | what the code is for, in one sentence |
| "1 kg, chocolate, eggless" | Inputs + output | the data you give it and exactly what it gives back |
| "Under ₹800, ready by 6 pm" | Constraints | rules the answer must follow: language, libraries, size, style |
| Shows a photo: "like this" | Example | one real input with the exact output you expect |
Anthropic's prompting guide has a good test: "Show your prompt to a colleague with minimal context on the task and ask them to follow it. If they'd be confused, Claude will be too." It also says examples are "one of the most reliable ways to steer Claude's output format" (Be clear and direct).
Attempt 2: the same request with the recipe
Goal: a Python function settle(people, expenses) that tells my flatmates who pays whom.
Inputs: people is a list of names, like ["Ravi", "Neha", "Sam"].
expenses is a list of (payer, amount) pairs, amount in whole rupees.
Every expense is shared equally by everyone.
Output: return a list of strings like "Sam pays Ravi Rs 500".
Constraints: Python 3, standard library only, no classes,
under 25 lines. Do the maths in paise (integers).
Example: settle(["Ravi", "Neha", "Sam"], [("Ravi", 1200), ("Neha", 300)])
returns ["Sam pays Ravi Rs 500", "Neha pays Ravi Rs 200"].
Reply with only the code and a 3-line example call.
- A function is a named block of code: you give it inputs, it gives back an answer.
- A list is items in square brackets:
["Ravi", "Neha", "Sam"]. A pair (a tuple) is two values in round brackets:("Ravi", 1200). - The standard library is the toolbox that comes with Python: nothing extra to install.
- Paise: whole numbers avoid the decimal-money problem from Episode 1.
- We checked the example's maths ourselves before sending it (₹1,500 / 3 = ₹500 each).
The real reply, 19 lines:
def settle(people, expenses):
paid = {p: 0 for p in people}
for payer, amt in expenses:
paid[payer] += amt * 100 # paise
base, extra = divmod(sum(paid.values()), len(people))
bal = {p: paid[p] - base - (i < extra) for i, p in enumerate(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
Reading it top-down:
- Lines 2-4: add up what each person paid, in paise. {p: 0 for p in people} is a dictionary: a name and a number next to it, like a register.
- Lines 5-6: divmod gives the equal share and the leftover paise (Episode 1). Balance = paid − share.
- Lines 7-19: match people who owe with people who are owed, biggest first, and write each payment as a sentence.
Run it, test it
flat = ["Ravi", "Neha", "Sam"]
print(settle(flat, [("Ravi", 1200), ("Neha", 300)])) # the example
print(settle(flat, [("Ravi", 1000)])) # 1000 / 3: uneven
print(settle(flat, [("Ravi", 1000), ("Neha", 500), ("Sam", 500)]))
Real output:
['Sam pays Ravi Rs 500', 'Neha pays Ravi Rs 200']
['Sam pays Ravi Rs 333.33', 'Neha pays Ravi Rs 333.33']
['Neha pays Ravi Rs 166.67', 'Sam pays Ravi Rs 166.66']
- Line 1 matches our example exactly.
- Line 2 is an edge case: an unusual input at the edges, where bugs hide. ₹1,000 doesn't split evenly by 3; Ravi's own share takes the leftover paisa (₹333.34), so no paisa is lost.
- Keep these test lines in the file and re-run them after every change.
Bad prompt vs good prompt
| One line | The recipe | |
|---|---|---|
| Prompt | write code to split expenses |
goal + inputs + output + constraints + example |
| Size | 84 lines | 19 lines |
| People, money | Alice/Bob/Carol, dollars | Ravi/Neha/Sam, rupees |
| Matches what Ravi needs | no | yes, first run |
| Can Ravi explain it? | no | yes |
Always name the language and the libraries
- Language: Python, JavaScript, Java... and where it runs (browser, server, laptop).
- Library: ready-made code someone else wrote that you add to your project (npm and pip packages, Episode 3).
- "Standard library only" = nothing to install. Or name the exact library: "use Chart.js for the chart" (Episode 11).
- Leave it open and the AI may pick a library you don't have, or invent one (
paytm_split, Episode 1).
Iterating: one change at a time (tasting while you cook)
Iterating = ask for a change, check the result, ask again. Add salt, taste. Add salt, chilli and sugar at once, and if it tastes wrong you can't tell which one did it.
ravi@laptop:~/q$ claude -p --continue 'One change: amounts can now have paise, like ("Neha", 99.50). Keep everything else the same. Reply with only the changed lines.'
--continue = same conversation, so the AI still sees its code. The real reply, complete:
paid[payer] += round(amt * 100) # paise
Why round and not int? Run it:
# Why the AI wrote round(amt * 100), not int(amt * 100)
print(0.29 * 100)
print(int(0.29 * 100))
print(round(0.29 * 100))
28.999999999999996
28
29
Decimal numbers (floats) are stored in binary and most can't be stored exactly. int() chops off the decimals and loses a paisa; round() gives 29. For money: round to paise, never just int().
A real AI mistake: five changes in one prompt
ravi@laptop:~/q$ claude -p --continue "Now change all of this at once: amounts can have paise; show money as ₹ with Indian commas like ₹1,20,000.50; names are case-insensitive; an expense can be split among only some people, given as a third item, like (\"Ravi\", 600, [\"Ravi\", \"Sam\"]); and sort the output by amount, biggest first. Reply with only the full new code."
Real reply: 68 lines with from decimal import Decimal, ROUND_HALF_UP and three new functions, ending with "I couldn't write this to settle.py or run it, because file-write and run permissions were denied. It's untested." The "under 25 lines" constraint from the first prompt was quietly dropped.
The 68-line version (for reference)
from decimal import Decimal, ROUND_HALF_UP
def to_paise(amt):
"""Convert an amount (int, float, str, Decimal) to integer paise."""
d = Decimal(str(amt)) * 100
return int(d.quantize(Decimal(1), rounding=ROUND_HALF_UP))
def inr(paise):
"""Format paise as ₹ with Indian digit grouping, e.g. ₹1,20,000.50."""
rs, ps = divmod(paise, 100)
s = str(rs)
if len(s) > 3:
head, tail = s[:-3], s[-3:]
groups = []
while len(head) > 2:
groups.insert(0, head[-2:])
head = head[:-2]
if head:
groups.insert(0, head)
s = ",".join(groups + [tail])
return f"₹{s}.{ps:02d}" if ps else f"₹{s}"
def settle(people, expenses):
# Case-insensitive names; canonical spelling comes from `people`.
canon = {}
for p in people:
canon.setdefault(p.casefold(), p)
names = list(canon.values())
def lookup(name):
try:
return canon[name.casefold()]
except KeyError:
raise ValueError(f"Unknown person: {name!r}") from None
balance = {p: 0 for p in names} # paise: paid - owed
for exp in expenses:
payer, amt, *rest = exp
payer = lookup(payer)
total = to_paise(amt)
if total < 0:
raise ValueError(f"Negative amount for {payer}")
if rest and rest[0] is not None:
group = list(dict.fromkeys(lookup(n) for n in rest[0]))
else:
group = names
if not group:
raise ValueError("An expense needs at least one person to split among")
base, extra = divmod(total, len(group))
balance[payer] += total
for i, p in enumerate(group):
balance[p] -= base + (i < extra)
debt = sorted([[-b, p] for p, b in balance.items() if b < 0], reverse=True)
cred = sorted([[b, p] for p, b in balance.items() if b > 0], reverse=True)
txns, i, j = [], 0, 0
while i < len(debt) and j < len(cred):
x = min(debt[i][0], cred[j][0])
txns.append((x, f"{debt[i][1]} pays {cred[j][1]} {inr(x)}"))
debt[i][0] -= x
cred[j][0] -= x
i += debt[i][0] == 0
j += cred[j][0] == 0
txns.sort(key=lambda t: -t[0]) # biggest first (stable for ties)
return [text for _, text in txns]
Re-running the old test lines on it:
ravi@laptop:~/q$ python3 -c 'from big import settle; print(settle(["Ravi","Neha","Sam"], [("Ravi",1000),("Neha",500),("Sam",500)]))'
['Neha pays Ravi ₹166.67', 'Sam pays Ravi ₹166.65']
| Sam pays Ravi | |
|---|---|
| Before (19-line version) | Rs 166.66 |
| After (68-line version) | ₹166.65 |
Nobody asked for that. The new code splits each expense separately and every time gives the leftover paisa to the first person in the list (Ravi 1,000 → 333.34/333.33/333.33; Neha 500 and Sam 500 → 166.67/166.67/166.66 each), so Sam's share ends up one paisa lower. It's a defensible choice, but a new one, made silently. A regression is something that used to work (or used to give a certain answer) and changes after an edit. With five changes in one go, you can't even tell which one caused it.
The fix: ask for a plan first (the electrician)
Before an electrician drills, you ask where the wires will go. For a bigger change, ask for the plan first: steps in plain words, no code. Claude Code also has a plan permission mode (claude --help lists --permission-mode ... plan).
ravi@laptop:~/q$ claude -p --continue "Next I want one change: an expense can be split among only some people, given as a third item, like (\"Ravi\", 600, [\"Ravi\", \"Sam\"]). Before writing any code, give me a short plan in at most 4 steps, and list one edge case to test. No code yet."
Real reply:
**Plan**
1. Accept expenses as either 2-tuples or 3-tuples. If the third item is missing, the split
is everyone in `people`.
2. For each expense, convert the amount to paise. Split it among that expense's
participants, and give the leftover paise to the first participants in the list.
Subtract each participant's share from their balance. Do this per expense, not on the
grand total, so each expense's rounding is correct.
3. Add the full amount to the payer's balance. The payer is credited even if they aren't
in the split list.
4. Leave the matching of debtors to creditors and the output formatting as they are.
**Edge case to test:** the payer isn't one of the participants. For example,
`settle(["A","B","C"], [("A", 100, ["B","C"])])` should give
`["C pays A Rs 50", "B pays A Rs 50"]`. A should be owed the full amount and owe nothing.
Step 2 states, in plain words, the exact rounding decision the 68-line version made silently. This time Ravi reads it before any code exists and accepts it. Then: "Plan approved. Write the full new settle function now. Keep it under 25 lines. Reply with only the code." Real reply, 22 lines:
def settle(people, expenses):
bal = {p: 0 for p in people}
for payer, amt, *rest in expenses:
paise = round(amt * 100)
parts = rest[0] if rest else people
base, extra = divmod(paise, len(parts))
bal[payer] += paise
for k, p in enumerate(parts):
bal[p] -= base + (k < extra)
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
Only lines 3-9 changed (for payer, amt, *rest in expenses: takes an optional third item; each expense is split with divmod among just its people). The matching and the sentences are unchanged, as step 4 promised.
Taste it again
flat = ["Ravi", "Neha", "Sam"]
print(settle(flat, [("Ravi", 1200), ("Neha", 300)])) # old example
print(settle(flat, [("Ravi", 600, ["Ravi", "Sam"])])) # new: only 2 share
print(settle(flat, [("Ravi", 100, ["Neha", "Sam"])])) # the AI's edge case
print(settle(flat, [("ravi", 500)])) # a typo
Real output:
['Sam pays Ravi Rs 500', 'Neha pays Ravi Rs 200']
['Sam pays Ravi Rs 300']
['Sam pays Ravi Rs 50', 'Neha pays Ravi Rs 50']
Traceback (most recent call last):
...
KeyError: 'ravi'
- Old example, new feature and the AI's own edge case all pass.
KeyError: 'ravi': you looked up a key the dictionary doesn't have ("Ravi" ≠ "ravi"). That's the next one-change prompt: "If a name isn't in people, raise a clear error."- After each step that works:
git commit(Episode 3), so a bad step is one command away from undone.
The loop for every feature
- Plan (if the change is big) → 2. one change → 3. read it top-down → 4. run tests, old and new → 5. commit.
- Keep your example lines; add one for every bug you find, so it can't come back unnoticed.
- For a big job, number the steps yourself ("Step 1 of 3: ..."). Anthropic's guide: give "sequential steps using numbered lists" when order matters.
- When something fails, paste the exact error back, word for word.
Common mistakes (real)
| What you did | What you got | Why | Fix |
|---|---|---|---|
write code to split expenses |
84 lines, JSON, Alice/Bob, dollars | every blank filled with a guess | goal, inputs, output, constraints, example |
int(0.29 * 100) |
28 |
floats aren't exact in binary | round(amt * 100); keep money in paise |
| five changes in one prompt | Sam 166.66 → 166.65, 68 lines, untested | a big change nobody re-tested | one change at a time, plan first, re-run old tests |
settle(flat, [("ravi", 500)]) |
KeyError: 'ravi' |
the name isn't in the dictionary | fix the input, or ask for a clear error message |
Mini project: your own settle()
- Write a recipe prompt for
settle()(goal, inputs, output, constraints, example) and send it to any AI assistant. - Paste the code into the SyntaxPilot compiler with four test lines: the example, ₹1,000 by Ravi alone, everyone paid something, and one with a typo.
- Ask for ONE change: unknown names raise
ValueError("Unknown name: ravi"). - Re-run all four test lines.
Solution (one correct version of the change)
def settle(people, expenses):
bal = {p: 0 for p in people}
for payer, amt, *rest in expenses:
parts = rest[0] if rest else people
for name in [payer, *parts]:
if name not in bal:
raise ValueError(f"Unknown name: {name}")
paise = round(amt * 100)
base, extra = divmod(paise, len(parts))
bal[payer] += paise
for k, p in enumerate(parts):
bal[p] -= base + (k < extra)
# ... the rest is unchanged from the 22-line version above
settle(flat, [("ravi", 500)]) now raises ValueError: Unknown name: ravi. The check runs before any balance changes, so a bad expense never half-updates the register.
Practice questions
- Name the five parts of the prompt recipe.
Answer
Goal, inputs, output, constraints, example.
- Rewrite this prompt with the recipe: "make a function for GST".
Sample answer
"Goal: a Python function add_gst(price, rate) that returns the price including GST. Inputs: price in rupees (may have paise), rate as a percent like 18. Output: the total in rupees rounded to 2 decimals. Constraints: Python 3, standard library only, under 10 lines, do the maths in paise. Example: add_gst(100, 18) returns 118.0."
- Why is "make all five changes at once" risky even if the AI is good?
Answer
The change is too big to read and test; if something breaks (like Sam's 166.66 → 166.65), you can't tell which change did it, and constraints from earlier prompts may be dropped.
- What does asking for a plan first buy you?
Answer
You see the AI's decisions (like how leftover paise are split) in plain words before any code exists, when they're cheapest to change.
print(int(1.15 * 100))prints114. Why, and what's the fix?
Answer
1.15 is stored as 1.149999..., so times 100 is 114.999...; int chops it to 114. Use round(1.15 * 100) → 115.
Quiz
Which part of the recipe is missing from this prompt?
Write a Python function that converts a price in rupees
to paise. Standard library only, under 10 lines.
It takes one number and returns a whole number.
A) The goal · B) The constraints · C) An example with its exact output · D) The language
Answer
C. It has the goal, the language, input, output and constraints, but no example like "99.50 returns 9950", which would also be a ready-made test.
Interview questions
- How do you prompt an AI coding tool for reliable output? State the goal, the exact inputs and output, constraints (language, libraries, size), and give an example input with its expected output; then iterate in small steps and test each one.
- Why should you ask an agent for a plan before a large change? It surfaces design decisions early, lets you correct them cheaply, and keeps the eventual change reviewable.
- What is a regression? A behaviour that used to be correct (or used to give a certain answer) changing after an edit. Catch it by re-running old tests after every change.
- Why store money as integers? Binary floating-point can't represent most decimal fractions exactly (
0.29 * 100 == 28.999999999999996), so sums and conversions drift; integer paise are exact.
Glossary
| Term | Meaning (plain words) | Example |
|---|---|---|
| Prompt | the message you give the AI | write code to split expenses |
| Goal | what the code is for, in one sentence | "tells my flatmates who pays whom" |
| Input | the data you give the code | people, expenses |
| Output | what the code gives back | ["Sam pays Ravi Rs 500", ...] |
| Constraint | a rule the answer must follow | "Python 3, under 25 lines" |
| Example (in a prompt) | one real input with the exact expected output | settle(...) returns [...] |
| Function | a named block of code that takes inputs and returns an answer | def settle(people, expenses): |
| List | items in square brackets, in order | ["Ravi", "Neha", "Sam"] |
| Pair / tuple | a few values grouped in round brackets | ("Ravi", 1200) |
| Dictionary | names (keys) with a value next to each, like a register | {"Ravi": 0, "Neha": 0} |
| Library | ready-made code someone else wrote, added to your project | Chart.js, decimal |
| Standard library | the libraries that come with the language | fractions, decimal, json |
| JSON | a text format for data | [{"payer": "A", "amount": 30}] |
divmod |
gives the whole-number share and the remainder together | divmod(100000, 3) → (33333, 1) |
| Float | a decimal number stored in binary; often not exact | 0.29 * 100 → 28.999999999999996 |
round() / int() |
round to the nearest whole number / chop off the decimals | round(28.99) → 29, int(28.99) → 28 |
| Test line | a line that runs the code on a known input to check the answer | print(settle(flat, ...)) |
| Edge case | an unusual input at the edges, where bugs hide | ₹1,000 split 3 ways |
| Iterating | change, check, change again | one change per prompt |
--continue |
Claude Code: continue the same conversation | claude -p --continue "..." |
| Regression | an old answer changing after an edit | Sam 166.66 → 166.65 |
| Plan first | ask for the steps in plain words before any code | "No code yet" |
| Plan mode | Claude Code's permission mode for planning without editing | --permission-mode plan |
| KeyError | Python error: you looked up a key the dictionary doesn't have | KeyError: 'ravi' |
| Commit | a Git save point (Episode 3) | git commit -m "..." |
Summary
- A short prompt means more guesses, not less code.
- The recipe: goal, inputs, output, constraints, example. Name the language and the libraries.
- Read the code top-down, and run it with test lines, including edge cases.
- Iterate one change at a time; for big changes, ask for a plan first.
- Re-run old tests after every change to catch regressions. Money: integer paise,
round()notint().
Next episode: Writing a spec before you build: user stories, features vs non-goals, acceptance criteria, and a one-page spec you feed to the AI.