How to Prompt an AI for Code (That Actually Works)
A good prompt is like a good job ticket. Say what to build, the inputs, the output, the rules and one example. Then the AI gets it right the first time.
In short: Goal + Language + Input/Output + Rules + Example. Ask for small pieces. Ask for tests too.
Why prompts matter
The AI cannot read your mind. A vague prompt gives vague code. Then you spend more time and more tokens fixing it. A clear prompt saves both.
What a good code prompt has
- Goal: one sentence: what the code must do.
- Language and tools: Python 3.12, Node 20, Java 21, “no extra libraries”.
- Input and output: the types and shape, e.g. “takes a price (float) and coupon (string) and returns a float”.
- Rules / edge cases: what to do on empty input, negative numbers, bad values.
- Example: one input and the exact expected output.
- Format: “only the code” or “code + a short explanation”.
How a prompt turns into working code
Bad prompt vs good prompt
write discount code
Write a Python 3 function final_price(price, coupon=None). SAVE10 gives 10% off. FLAT50 gives 50 off. The result is never below 0 and is rounded to 2 decimals. Raise ValueError for a negative price or an unknown coupon. Example: final_price(200, "SAVE10") returns 180. Only return the code.
The code the AI wrote (tested here)
discount.pydef final_price(price: float, coupon: str | None = None) -> float:
"""Return price after coupon. SAVE10 = 10% off, FLAT50 = 50 off. Never below 0."""
if price < 0:
raise ValueError("price cannot be negative")
if coupon == "SAVE10":
price = price * 0.9
elif coupon == "FLAT50":
price = price - 50
elif coupon is not None:
raise ValueError(f"unknown coupon: {coupon}")
return round(max(price, 0), 2)Write pytest tests for final_price: no coupon, SAVE10, FLAT50 on a small price, and an unknown coupon.
import pytest
from discount import final_price
def test_no_coupon():
assert final_price(200) == 200
def test_save10():
assert final_price(200, "SAVE10") == 180
def test_flat50_never_negative():
assert final_price(30, "FLAT50") == 0
def test_bad_coupon():
with pytest.raises(ValueError):
final_price(100, "FREE")pip install pytest
pytest -q
# -> 4 passedHow to write prompts, step by step
- Start with the goal in one sentence.
- Name the language, version and libraries.
- Give the function name and inputs/outputs.
- List the edge cases (empty, zero, negative, wrong type).
- Add one example with the exact output.
- Say the format: “only the code”.
- Ask for tests in a follow-up, then run them.
- Fix with a short follow-up: paste only the failing test and error lines.
Same pattern in other stacks
- JavaScript: “Write a Node 20 function
slugify(title), no npm packages, return lowercase words joined by dashes. Example: “Hello, World!” → “hello-world”.” - Java: “Write a Java 21 static method
isStrong(String pw): at least 8 chars, one upper, one lower, one digit. Null returns false. Add JUnit 5 tests.” - SQL: “PostgreSQL. Table orders(id, customer_id, amount, created_at). Write a query for total amount per customer in 2026, highest first.”
Settings and config: save your rules once
Most tools read a project file with your standing rules. Then you do not repeat them in every prompt.
- GitHub Copilot: create
.github/copilot-instructions.mdin your repo. Write rules like “Use Python 3.12, pytest, type hints”. - Claude Code: create
CLAUDE.mdin the project root (or run/initto make one). Put the same rules there. - Keep it short. These files are sent with requests, so a long file costs tokens every time.
Quick quiz
1. Name the five parts of a good code prompt.
Goal, language/tools, input/output, rules/edge cases, example.
2. Why add one example?
It shows the exact output you expect, so the AI has less to guess.
3. A test fails. What do you send back?
Only the failing test and the error lines, with a short ask to fix it.
4. Where do you save project rules for Copilot?
In .github/copilot-instructions.md.
Save tokens and money
Ask for one function at a time. Add “only the code”. Paste only the lines that matter, not the whole file. Put standing rules in a short instructions file instead of retyping them.