Iterative Refinement with Claude Code: Input/Output Examples, Tests First and the Interview Pattern
"Format the phone numbers nicely" gives a different format each run. Three input/output examples fix the target, five tests written first catch two edge cases in the first draft, and the failing pytest output is what you hand back.
What you will learn
- Steer Claude Code with two or three input/output examples when words are read differently
- Write the tests first and hand back the failing test output instead of re-describing the problem
- Use the interview pattern so Claude asks questions before building in unfamiliar territory
- Send interacting problems in one message and independent ones one at a time
Before you start
- Using Claude Code in a terminal
- Basic pytest
You ask Claude Code: format the phone numbers nicely. You run it and the answer looks fine. You run it again and the format is different. In the lecture's illustration, one run gives 555-123-4567, another (555) 123-4567, another +1 555 123 4567. Each is a fair reading of the words. But the checkout form wants exactly one format.
Words can be read more than one way, so the result drifts. Three tools do most of the steering: examples, tests first, and the interview. Here's when to reach for each, using the lecture's small S05L05_ShopApp project.
Show it, don't describe it
You visit a tailor and say "make it fit". Too tight, too long, too wide: the tailor has to guess. Now hand over a shirt that already fits and say "copy this one". The tailor matches it, and you get the same fit every time. An example says in one glance what a paragraph of words only hints at.
Examples: two or three input/output pairs
The project's EXAMPLES.md holds the pairs you paste into the prompt:
# Phone number examples (paste these into the prompt)
| Input | Output |
|--------------------|----------------|
| `555 123 4567` | `555-123-4567` |
| `(555) 123-4567` | `555-123-4567` |
| `1-555-123-4567` | `555-123-4567` |
Edge cases: an empty string and None both give an empty string.
Spaces become dashes, brackets go, and a leading country code 1 is dropped. In the lecture, a new number with dots, 555.222.3333, which Claude has never been shown, comes back as 555-222-3333: the pattern is followed. Two or three examples are enough. You don't need twenty.
Use examples when a description keeps being read differently. For how many to give and how to pick them, see few-shot prompting done right.
Tests first
Each example also becomes a test. Write the tests before the code:
from format_phone import format_phone
def test_spaces():
assert format_phone("555 123 4567") == "555-123-4567"
def test_brackets():
assert format_phone("(555) 123-4567") == "555-123-4567"
def test_country_code():
assert format_phone("1-555-123-4567") == "555-123-4567"
def test_empty_string():
assert format_phone("") == ""
def test_none():
assert format_phone(None) == ""
Three tests come straight from the examples: given this input, check for this exact output. The last two are edge cases, an empty string and None. These are the cases that break first, so write them down now. A good suite covers the expected behaviour, the edge cases, and any speed requirement you have.
Then ask Claude Code to make them pass, and say clearly that it must not change the tests:
"Make the tests in test_format_phone.py pass. Do not change the tests. Run pytest and show me what fails."
Tests turn a vague goal into checks a machine can run. That's the same move as in explicit criteria vs vague prompts, applied to code.
Share the failures
Here is a first draft, written from the prose request only:
"""First draft: written from the prose request only."""
def format_phone(raw):
digits = "".join(ch for ch in raw if ch.isdigit())
if len(digits) == 11 and digits.startswith("1"):
digits = digits[1:]
return f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"
Run pytest -q against it:
...FF
=== FAILURES ===
test_format_phone.py:17: AssertionError: assert '--' == ''
format_phone.py:5: TypeError: 'NoneType' object is not iterable
=== short test summary info ===
FAILED test_format_phone.py::test_empty_string
FAILED test_format_phone.py::test_none
2 failed, 3 passed in 0.01s
Three pass, two fail, and both failures are edge cases. The empty string comes back as '--' (three empty slices joined by two dashes), and None crashes the loop over characters.
Now the important habit: don't describe the problem again in your own words. Paste the failures. The test names and messages say exactly what's wrong:
"Two tests fail: test_empty_string and test_none. Here is the pytest output. Fix format_phone so all five pass."
The fixed function adds one guard at the top:
"""Tidy a phone number for the shop-app checkout form."""
def format_phone(raw):
"""Return a 10-digit number as 555-123-4567; None or empty gives ''."""
if not raw:
return ""
digits = "".join(ch for ch in raw if ch.isdigit())
if len(digits) == 11 and digits.startswith("1"):
digits = digits[1:]
return f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"
Same command again:
.....
5 passed in 0.01s
All five pass. Each round becomes a clear question, and the failures are the answer you hand back. (Both outputs were recorded by running pytest -q --tb=line on the draft and on the project's files, trimmed to the key lines. Running the tests needs no model and no API key.)
The interview pattern
Sometimes you can't write examples or tests yet, because the area is new to you. Say you ask Claude to add a cache for product prices. Instead of building straight away, ask it to question you first:
"Before you build a cache for product prices, ask me questions about anything I might not have thought of."
In the lecture, Claude comes back with three questions:
- How stale can a price be? That's how long to keep an entry.
- What if the price store is down? A failure mode: serve the old price, or fail.
- Who clears a price when it changes? Cache invalidation: someone has to tell the cache.
You answer, and the design fits your answers. The questions surface what you hadn't thought of yet. Ask first in unfamiliar territory, then build.
One message or many
You have several problems. Send them together, or one by one? Ask yourself: if I fix this one, can it change that one?
| Problems | Do they interact? | Send |
|---|---|---|
| Rounding happens first, currency is converted later; two prices look wrong | Yes: change one and the other shifts | One detailed message, with both examples and both expected outputs |
| A typo in a label, and a slow query | No: neither changes the other | One at a time: fix, check, then the next |
Fixing one interacting problem on its own would only move the other. Independent problems, on the other hand, are easier to verify one by one.
How this shows up in a question
The classic scenario: Claude Code transforms records in a migration script, and each run reads your written description a little differently. A longer description, or the same key words repeated, is still only words. Asking Claude to "be more careful" gives it nothing new. A bigger model still gets the same vague request. Adding two or three concrete input/output examples shows the transformation, and that's the fix.
Common mistakes
| Mistake | Do this instead |
|---|---|
| Rewriting the request in longer prose when output drifts | Add 2-3 input/output examples |
| Testing only the happy path | Add the edge cases (empty string, None) before the code exists |
| Letting Claude edit the tests to make them pass | Say "do not change the tests" |
| Describing a failure in your own words | Paste the pytest output |
| Asking for a build in an area you don't know | Ask Claude to interview you first |
| Splitting interacting bugs into separate messages | One message with every example and expected output |
Quick recap
| Tool | Use it when |
|---|---|
| Examples | A description keeps being read differently: give 2-3 input/output pairs |
| Tests first | You can state the behaviour: write tests, then share the failures each round |
| Interview | The territory is new: let Claude ask before it builds |
| One message | Problems interact; independent ones go one at a time |
The phone formatter project for this lesson is in the community, free to join.
Try it yourself
Add a sixth test for a number that's too short, such as "555 1234", and decide what it should return before you run anything. Run pytest -q, read the failure, and paste exactly that output into Claude Code as your next message.
Related course on Udemy
Claude Certified Architect - Foundations (CCAR-F) Exam Prep
Agentic loops, tools, MCP, Claude Code, prompts, structured output and context.View on Udemy ↗: Claude Certified Architect - Foundations (CCAR-F) Exam Prep (paid course, opens in a new tab)Related posts
CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
Three needs in one repo: a test command, a rule that Claude must never read .env, and a shared deploy skill. See which file each belongs in, how the settings layers merge, and what a plugin manifest carries.
Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
Pack a support team's ticket-triage routine into one skill folder, then watch three requests load one, two or all three levels: the catalog, the SKILL.md body, and a script whose code never enters the context.
One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
Change one line in a repo and ask where it lands. A small resolver for bookshop-bot shows that a new model id in settings.json reaches only CI, a prompt bump reaches dev and CI, and a prod block edit reaches only prod.
Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
Follow one prompt edit from a branch to a merge: version prompts and the model pin like code, keep the API key in GitHub Secrets, gate changes by path, let Claude review the diff, and leave the merge to a person.
