Lesson 23: Prompting for Code Generation
The CODE framework, before/after examples, and the mistakes that make AI write broken code.
Why Code Prompts Are Different
Code must be correct, not just plausible. Vague prompts produce confident-looking but broken code. The fix: give the model the contract — inputs, outputs, constraints, and examples.
The CODE Framework
| Letter | Element | What You Provide |
|---|---|---|
| C | Context | What is this for? What are the inputs? |
| O | Output | Function signature, return type, docstring |
| D | Dependencies | Libraries allowed/forbidden, versions |
| E | Examples | Input → expected output pairs |
Bad vs. Good Code Prompt
Bad:
Write a function to calculate the average of a list.
→ Ambiguous: what about empty lists? floats? rounding?
Good:
Write a Python function that computes the average of a list of numbers.
CONTEXT:
- Input: a list of floats, e.g. [10, 20, 30]
- Handle empty lists (return None)
OUTPUT:
- A function named average(values)
- Include a docstring and one usage example
DEPENDENCIES:
- Standard library only
EXAMPLE:
average([10, 20, 30]) -> 20.0
Edge Cases to Always Specify
- Empty input, single item, negative numbers, zero division.
- What to return on failure (None, error, exception?).
- Performance constraints (large inputs?).
- Mutating the input vs. returning a copy.
Ask for Tests, Then Verify
The professional workflow:
1. "Write the function per the spec."
2. "Now write 5 test cases including edge cases."
3. "Run the tests and fix any failures."
Never trust generated code blindly — run it, review it, and test edge cases yourself. AI code can be subtly wrong (off-by-one, wrong library API, security holes).
Common Code Prompt Mistakes
| Mistake | Fix |
|---|---|
| No signature/return spec | Define the exact interface |
| No example | Show input → output |
| No constraints | State allowed libraries and limits |
| No edge cases | Ask for edge-case handling explicitly |
| No tests | Chain a test-generation step |
Example: Refactor Request
Refactor this function to be faster and easier to test:
[code]
Keep the same public interface (same name, params, return).
Use only the standard library. Add a short comment explaining
the new approach.
Key Takeaways
- Code prompts need a contract: context, output, dependencies, examples (CODE).
- Specify edge cases explicitly and ask for tests.
- Verify generated code by running it — never trust it blindly.
- Keep the public interface stable when asking for refactors.
Next up: Prompting for writing and content — tone, audience, and the WRITE framework.
# The CODE framework: Context, Output, Dependencies, Examples
prompt = """Write a Python function that computes the average of a list of numbers.
CONTEXT:
- Input: a list of floats, e.g. [10, 20, 30]
- Handle empty lists (return None)
OUTPUT:
- A function named average(values)
- Include a docstring and one usage example
DEPENDENCIES:
- Standard library only
EXAMPLE:
average([10, 20, 30]) -> 20.0
"""
print(prompt)
# The generated code - verify it actually works
def average(values):
"""Return the mean of a list of numbers, or None if empty."""
if not values:
return None
return sum(values) / len(values)
print("Result:", average([10, 20, 30]))
print("Empty list:", average([]))Lesson Code (Python)
# The CODE framework: Context, Output, Dependencies, Examples
prompt = """Write a Python function that computes the average of a list of numbers.
CONTEXT:
- Input: a list of floats, e.g. [10, 20, 30]
- Handle empty lists (return None)
OUTPUT:
- A function named average(values)
- Include a docstring and one usage example
DEPENDENCIES:
- Standard library only
EXAMPLE:
average([10, 20, 30]) -> 20.0
"""
print(prompt)
# The generated code - verify it actually works
def average(values):
"""Return the mean of a list of numbers, or None if empty."""
if not values:
return None
return sum(values) / len(values)
print("Result:", average([10, 20, 30]))
print("Empty list:", average([]))Console Output
Write a Python function that computes the average of a list of numbers.
CONTEXT:
- Input: a list of floats, e.g. [10, 20, 30]
- Handle empty lists (return None)
OUTPUT:
- A function named average(values)
- Include a docstring and one usage example
DEPENDENCIES:
- Standard library only
EXAMPLE:
average([10, 20, 30]) -> 20.0
Result: 20.0
Empty list: NoneCode Visualization Tips
- Draw the CODE framework as a 4-box spec sheet the model must fill in.
- Show bad vs. good code prompts side by side, annotating what each added line fixes.
- Sketch the verify loop: generate → test → fix → re-test until green.
Professional Tips & Tricks
- Include one runnable example pair — models infer intent from examples better than prose.
- Ask for tests FIRST, then code — the tests act as a spec.
- For refactors, paste the current interface and forbid changing it.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Write a CODE Prompt
Test Your Knowledge
Instant feedbackQuick Check: Prompting for Code
Up next · Continue learning
Prompting for Writing & Content
The WRITE framework for audience, tone, and format — with before/after examples for posts, emails, and articles.