Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 1

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

WHY

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

WHAT
  • 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

1 · Write the goal one clear sentence 2 · Add rules + example edge cases, sample output 3 · AI writes code read it 4 · Ask for tests run them 5 · Fix with small follow-ups paste only the error

Bad prompt vs good prompt

BAD PROMPT

write discount code

GOOD PROMPT (COPY THIS PATTERN)

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.py
def 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)
FOLLOW-UP PROMPT

Write pytest tests for final_price: no coupon, SAVE10, FLAT50 on a small price, and an unknown coupon.

test_discount.py
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 passed

How to write prompts, step by step

HOW
  1. Start with the goal in one sentence.
  2. Name the language, version and libraries.
  3. Give the function name and inputs/outputs.
  4. List the edge cases (empty, zero, negative, wrong type).
  5. Add one example with the exact output.
  6. Say the format: “only the code”.
  7. Ask for tests in a follow-up, then run them.
  8. 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.

  1. GitHub Copilot: create .github/copilot-instructions.md in your repo. Write rules like “Use Python 3.12, pytest, type hints”.
  2. Claude Code: create CLAUDE.md in the project root (or run /init to make one). Put the same rules there.
  3. Keep it short. These files are sent with requests, so a long file costs tokens every time.
Rule: never put passwords, API keys or customer data in a prompt or an instructions file.

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

SMART AI USE

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.

Save these cards

INTERVIEW CARDAI Coding

What makes a good code prompt?

Goal + language + input/output + edge cases + one example + format.
Then ask for tests and run them.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Vague vs clear prompt

Vague: “write discount code” → guesses, rework.
Clear: name, rules, example → right first time, 4 tests pass.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Prompt formula

G-L-I-R-E-F: Goal, Language, In/Out, Rules, Example, Format.
Small pieces. Tests next. Short fixes.
Ravindra Bagale · ravindrabagale.com/ai-coding
Next in this course: see all chapters on the AI Coding page.