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.
Ravindra Bagale's Tip
Before you ask an AI for code, write one example input and the exact output on paper or in a comment. That one line often shows what is missing in a vague prompt sooner than a long chat.
Ravindra Bagale's Tip – मराठी
AI ला code मागण्यापूर्वी paper वर किंवा comment मध्ये एक example input आणि exact output लिहा. यामुळे prompt मध्ये काय missing आहे ते लवकर समजतं.
Ravindra Bagale's Tip – हिंदी
AI से code माँगने से पहले paper पर या comment में एक example input और exact output लिखो. इससे जल्दी समझ आता है कि prompt में क्या missing है.
Hello friends. Today we practice one clear prompt and then we run a small test so we can see whether this example works. Keep the practice data fictional. Do not paste real passwords or customer names. Passing these tests does not prove every possible case is correct.
नमस्कार मित्रांनो. आज आपण एक clear prompt लिहून पाहू आणि नंतर एक छोटा test चालवून या example मध्ये काय होते ते पाहू. Practice data fictional ठेवा. खरं password किंवा customer name paste करू नका. हे tests pass झाले म्हणजे प्रत्येक possible case सिद्ध झाला असे नाही.
नमस्कार दोस्तों. आज हम एक clear prompt लिखकर देखेंगे और फिर एक छोटा test चलाकर इस example में क्या होता है यह देखेंगे. Practice data fictional रखो. असली password या customer name paste मत करना. ये tests pass होना हर possible case की पूरी गारंटी नहीं है.
Try this yourself: clamp a number with a clear prompt
Python 3.13.5 and pytest 9.2.0. Use Python 3.10+ (needed for list[float] style hints as written). Create a folder on your computer, open a terminal in that folder, then set up a venv and install pytest before you run tests.Fictional practice data only. No real accounts or secrets.
Your task: create a file named clamp.py and write a Python 3 function clamp(value, low, high) that keeps a number inside an inclusive range. If value is below low, return low. If value is above high, return high. Otherwise return value. If low is greater than high, raise ValueError. Example: clamp(15, 0, 10) returns 10. Use only the Python standard library.
Also create a file named test_clamp.py using the tests block below (save the filename exactly).
- Create a project folder and open a terminal inside it.
- Create a venv: on macOS/Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv(orpython -m venv .venvif that is your Python 3 launcher). - Activate the venv: macOS/Linux
source .venv/bin/activate. Windows Command Prompt.venv\Scripts\activate.bat. Windows PowerShell.venv\Scripts\Activate.ps1. - Install pytest in the venv:
python -m pip install pytest(after activation,pythonshould be the venv interpreter). - Save your function in a new file named
clamp.pyin the same folder as your venv. - Write one clear prompt for yourself or for an AI that names the function, the three inputs, the range rules, the
ValueErrorrule whenlow > high, and the exampleclamp(15, 0, 10) → 10. - Implement
clampinclamp.pyfrom that prompt (standard library only). - Save the tests below as
test_clamp.pyin the same folder. - Run:
python -m pytest -q test_clamp.pyand expect the exact output line4 passed.
Tests — save as test_clamp.py
"""Tests for fictional clamp practice."""
from clamp import clamp
import pytest
def test_inside_range():
assert clamp(5, 0, 10) == 5
def test_below_low():
assert clamp(-3, 0, 10) == 0
def test_above_high():
assert clamp(15, 0, 10) == 10
def test_bad_bounds():
with pytest.raises(ValueError):
clamp(1, 5, 2)
Command and expected output (venv active):
terminalpython -m pytest -q test_clamp.py
# -> 4 passed
Optional solution for clamp.py (try yourself first)
Use this only after you attempt the task. Save or compare against your clamp.py file.
"""Fictional practice: keep a number inside a range."""
def clamp(value: float, low: float, high: float) -> float:
"""Return value limited to the inclusive range [low, high]."""
if low > high:
raise ValueError("low cannot be greater than high")
if value < low:
return low
if value > high:
return high
return value
Troubleshooting this exercise
- Symptom:
ModuleNotFoundErrorforclamporpytest— Fix: confirm the venv is active, both files are in the current folder, then re-runpython -m pip install pytestand the same pytest command. - Symptom: a test expects
10but you returned15— Fix: whenvalue > high, returnhigh, then re-run the same command. - Symptom:
low > highdid not raise — Fix: raiseValueErrorbefore clamping, then re-run.
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.