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.

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.

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.

Try this yourself: clamp a number with a clear prompt

Environment (tested): these exercises were verified with 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).

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a venv: on macOS/Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv (or python -m venv .venv if that is your Python 3 launcher).
  3. Activate the venv: macOS/Linux source .venv/bin/activate. Windows Command Prompt .venv\Scripts\activate.bat. Windows PowerShell .venv\Scripts\Activate.ps1.
  4. Install pytest in the venv: python -m pip install pytest (after activation, python should be the venv interpreter).
  5. Save your function in a new file named clamp.py in the same folder as your venv.
  6. Write one clear prompt for yourself or for an AI that names the function, the three inputs, the range rules, the ValueError rule when low > high, and the example clamp(15, 0, 10) → 10.
  7. Implement clamp in clamp.py from that prompt (standard library only).
  8. Save the tests below as test_clamp.py in the same folder.
  9. Run: python -m pytest -q test_clamp.py and expect the exact output line 4 passed.

Tests — save as test_clamp.py

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):

terminal
python -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.

clamp.py
"""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

HOW
  1. Symptom: ModuleNotFoundError for clamp or pytest — Fix: confirm the venv is active, both files are in the current folder, then re-run python -m pip install pytest and the same pytest command.
  2. Symptom: a test expects 10 but you returned 15 — Fix: when value > high, return high, then re-run the same command.
  3. Symptom: low > high did not raise — Fix: raise ValueError before clamping, then re-run.
Practice label: inputs and names on this block are fictional teaching samples, not real people or accounts. Passing the listed tests checks those examples only.

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.