Site

Prompting — Effective Prompts for Code

Tutorial 5.0  •  AI / Learn

5.0 What This Teaches

Getting good code out of an LLM depends less on which model you use and more on how you phrase the request. This tutorial covers:

5.1 Be Specific About Language and Version

Vague prompts produce generic output. Specific prompts constrain the model to exactly what you need.
VagueSpecific
"Write a sort function" "Write a Python 3.10 function that sorts a list of dicts by a given key. Include a type hint for the key parameter and a one-line docstring."
"Read a file" "Write a Python 3.10 function that reads a UTF-8 text file and returns its contents as a list of stripped lines. Include type hints."
The model has seen millions of sort functions in dozens of languages. Without constraints it picks the most common interpretation. Naming the language, version, type annotations, and docstring style removes ambiguity and produces output that fits directly into your codebase.
# specific_prompt.py - compare vague vs specific prompt output.
import anthropic

client = anthropic.Anthropic()

def ask(prompt: str) -> str:
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=256,
        messages=[{"role": "user", "content": prompt}]
    )
    return response.content[0].text

vague    = "Write a sort function."
specific = (
    "Write a Python 3.10 function that sorts a list of dicts by a given key. "
    "Include a type hint for the key parameter and a one-line docstring. "
    "Return only the code, no explanation."
)

print("--- Vague ---")
print(ask(vague))
print("--- Specific ---")
print(ask(specific))

5.2 Ask for Format Instructions

By default the model wraps code in explanation and prose. Tell it exactly what format you want, especially if you are parsing the output programmatically.
# format_json.py - request structured output and parse it.
import anthropic
import json

client = anthropic.Anthropic()

prompt = (
    "Write a Python function that checks whether a string is a palindrome. "
    "Return a JSON object with exactly two keys: "
    "'code' (the function as a string) and "
    "'explanation' (one sentence describing what it does). "
    "Return only the JSON object, no other text."
)

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=512,
    messages=[{"role": "user", "content": prompt}]
)

raw  = response.content[0].text
data = json.loads(raw)
print("Code:")
print(data["code"])
print("\nExplanation:", data["explanation"])
Common format instructions and when to use them:

5.3 Step-by-Step Reasoning

For algorithmic problems - sorting, graph traversal, dynamic programming - asking the model to reason before writing code often produces more correct output. Add the phrase "Think step by step before writing code." at the end of the prompt.
# chain_of_thought.py - ask the model to reason first.
import anthropic

client = anthropic.Anthropic()

prompt = (
    "Write a Python function that finds all pairs in a list of integers "
    "that sum to a given target value. "
    "Think step by step before writing code."
)

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=512,
    messages=[{"role": "user", "content": prompt}]
)

print(response.content[0].text)
The model will typically describe its approach first, then write the function. This reasoning step acts as a check - if the plan is wrong, the code is usually also wrong, and you can spot the error before running anything.

5.4 Few-Shot Examples

A few-shot prompt shows the model one or more input/output examples before presenting the actual task. The model learns the pattern from your examples and applies it to the new request.
# few_shot.py - teach style with one example then request a new function.
import anthropic

client = anthropic.Anthropic()

example = '''\
def multiply(a: int, b: int) -> int:
    """Return the product of a and b."""
    return a * b
'''

prompt = (
    f"Here is an example of the style I want:\n\n{example}\n"
    "Now write a function that divides two floats, following the same style: "
    "type hints, a one-line docstring, and no extra prose."
)

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=256,
    messages=[{"role": "user", "content": prompt}]
)

print(response.content[0].text)
Few-shot prompting is especially useful when you have a house style for docstrings, logging, or error handling that is hard to describe in words but easy to show.

5.5 Iterating on Prompts

AI output is rarely perfect on the first try. Treat prompt writing as a loop: generate, inspect the result, refine the prompt, generate again.
# prompt_loop.py - iterative prompt refinement.
import anthropic

client = anthropic.Anthropic()

prompts = [
    # iteration 1: too vague
    "Write a function to parse dates.",
    # iteration 2: added language and format spec
    "Write a Python 3.10 function to parse ISO 8601 date strings. Include type hints.",
    # iteration 3: added docstring and error handling requirement
    (
        "Write a Python 3.10 function to parse ISO 8601 date strings. "
        "Include type hints, a one-line docstring, and raise ValueError "
        "for invalid input. Return only the code."
    ),
]

for i, prompt in enumerate(prompts, start=1):
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=256,
        messages=[{"role": "user", "content": prompt}]
    )
    print(f"--- Iteration {i} ---")
    print(response.content[0].text)
    print()
Keep a prompt log - a plain text file or list - so you can track what changed between versions and roll back to a better prompt if a new refinement makes things worse.

5.6 Common Prompt Patterns

PatternExample phraseWhen to use
Only code "Return only the code, no explanation." Saving output directly to a source file
Step by step "Think step by step before writing code." Algorithms with non-obvious logic
Format as JSON "Return JSON with keys 'code' and 'explanation'." Programmatic processing of both parts
Explain each line "Add an inline comment to every line of code." Learning a new pattern or library
What could go wrong? "List edge cases and potential bugs in this code." Code review and hardening

5.7 Exercise

Exercise Write two versions of a prompt asking for a binary search implementation. The first version should be vague: "Write a binary search function." The second version should be fully specified: state the language (Python 3.10), require type hints on the function signature, require a docstring that describes the parameters and return value, and instruct the model to return only the code with no surrounding prose. Run both prompts and compare the output. Note which version requires less editing before you could commit it to a real codebase.

5.8 Common Mistakes

Assuming the model knows your codebase context

The model has no access to your files. If you ask it to "add error handling to my read_config function" without pasting the function into the prompt, it will invent a plausible function from scratch. Always include the relevant code in the prompt when asking for modifications.

Asking for too many things at once

"Write a REST client, add logging, include unit tests, and make it async." is four tasks. The model attempts all of them and often does each one poorly. Send one clear task per call and combine the results yourself.

Not specifying the programming language

"Write a function that reads environment variables" could be Python, Rust, JavaScript, or Go. The model picks the most statistically common answer for that phrase. If you want Python, say Python.

5.9 Key Terms

TermMeaning
promptThe text input you send to the model
prompt engineeringThe practice of crafting and refining prompts to improve model output
few-shotIncluding one or more input/output examples in the prompt to teach a style or pattern
chain-of-thoughtInstructing the model to reason step by step before producing its final answer
format instructionA directive in the prompt that specifies the shape of the output (JSON, code only, etc.)
specificityThe degree to which a prompt constrains the model's output to what you actually need