Prompting AI to Write Code
Reviewed & published by Brayan K
Getting good code from an AI comes down to giving it the right facts: the language and version, the goal, any constraints, and — when you’re fixing a bug — the exact error. You don’t need to be a programmer to do this well; you just need to be specific.
Part of the free Prompt Engineering course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
Just as important: never ship code you haven’t read and tested. This lesson covers both halves — writing a strong coding prompt, and checking what comes back.
What You'll Learn in This Lesson
- Always state the language and version
- Describe the goal and any constraints clearly
- Paste the full error and the line when fixing bugs
- Share the smallest snippet, not your whole repo
- Read and test the output before trusting it
- Ask the AI to explain code you don't understand
1 Give the language, version, and goal
The model can’t see your machine. Spell out the environment and what success looks like. Same task, two prompts:
write me code to read a file
and add up the numbersNo language, no version, no format — the model has to guess all of it.
Python 3.11. Write a function that reads a
CSV file of sales (columns: date, amount)
and returns total revenue per month.
No new libraries. Handle an empty file.
Add a one-line comment explaining each step.Language, version, goal, constraints, and an edge case — nothing left to guess.
2 Fixing a bug? Paste the error and the line
The exact error message is the highest-value thing you can hand a coding assistant. Report facts, not feelings:
the total is wrong, fix my codePython 3.11. This loop crashes with:
TypeError: unsupported operand type(s)
for +: 'int' and 'str' (line 7)
amount comes from a CSV as a string.
Convert it to a number before adding.3 Read and test before you trust
AI can be confidently wrong — inventing a function, missing an edge case, or producing a quiet bug. Treat every answer as a draft to verify:
- Read it — does each step make sense? Ask “explain line 8” if not.
- Run it — on real and tricky inputs (empty, huge, weird characters).
- Ask for a test — “add one test that proves this handles an empty file.”
- Check the edges — “what inputs would break this?”
📋 Copy-paste coding-prompt template
Language + version: <e.g. Python 3.11>.
Goal: <what the code should do>.
Constraints: <no new libs / under 20 lines / handle empties>.
<If fixing a bug, paste the snippet + full error + line.>
Please write the code, add brief comments, and
note any edge cases it does NOT handle.Try it for real
The highest-value habit when asking for code is pasting the tests alongside the request. Run this: the function looks fine and passes five cases, then raises a ValueError on \1h30m\ — an input nobody thought to mention. A prose spec cannot catch that. Six lines of test can, in ten seconds.
# The single highest-value habit when asking for code: send the tests with the
# request. A spec in prose is arguable; a failing test is not.
def parse_duration(text):
"""Model-written: turn '1h 30m' into total minutes."""
total = 0
for part in text.split():
if part.endswith("h"):
total += int(part[:-1]) * 60
elif part.endswith("m"):
total += int(part[:-1])
return total
# The tests you would have pasted into the prompt alongside the request.
cases = [
("1h 30m", 90),
("2h", 120),
("45m", 45),
("", 0),
("90m", 90),
("1h30m", 90), # no space — the format a user will type sooner or later
]
failed = []
for text, expected in cases:
# A real test runner treats a crash as a failure, not as the end of the run.
try:
got = parse_duration(text)
ok = got == expected
except Exception as e:
got, ok = f"{type(e).__name__}: {e}", False
if not ok:
failed.append((text, expected, got))
print(f" {'PASS' if ok else 'FAIL'} parse_duration({text!r}) -> {got} (want {expected})")
print()
print(f"{len(cases) - len(failed)}/{len(cases)} passed")
print()
print("The last case is why this matters. The code is not wrong exactly — it is")
print("wrong about an input nobody thought to mention, and it does not return a")
print("bad answer, it raises. Shipped without a test, that is a crash in front of")
print("a user. Pasting these six cases into the prompt turns an arguable prose")
print("spec into something you can check in ten seconds.")# 🎯 YOUR TURN — write the test loop that checks model-written code.
def to_initials(name):
"""Model-written: 'ada lovelace' -> 'A.L.'"""
return ".".join(p[0].upper() for p in name.split()) + "."
cases = [
("ada lovelace", "A.L."),
("grace brewster hopper", "G.B.H."),
("linus", "L."),
]
failures = 0
for name, expected in cases:
got = to_initials(name)
# 1) The case fails when the result differs from what you specified.
if got ___ expected:
# 👉 replace ___ with !=
failures += 1
print(f"{name!r} -> {got!r}")
# 2) Report how many of the cases did not hold.
print("failures:", ___)
# 👉 replace ___ with failures
# ✅ Expected output:
# 'ada lovelace' -> 'A.L.'
# 'grace brewster hopper' -> 'G.B.H.'
# 'linus' -> 'L.'
# failures: 0Common Mistakes (and the fix)
- No language or version. — “Python” vs “Python 3.12” can be the difference between right and wrong.
- Describing the error instead of pasting it. — Paste the full traceback verbatim.
- Dumping the whole repo. — Give the smallest reproducible snippet.
- Shipping unread code. — Read, test, and ask it to explain before you trust it.
⏱ Test Yourself — Timed Quiz
10 quick questions, 12 seconds each. Instant feedback — beat the clock!
🎉 Lesson Complete
- ✅ Always state the language and version plus the goal
- ✅ Add constraints so the code fits your real project
- ✅ Fixing a bug? Paste the full error and the line
- ✅ Share the smallest snippet, not the whole repo
- ✅ Always read and test before you trust AI-written code
Practice quiz
When asking AI to write code, what should you always state?
- Your mood
- The weather
- The language and version
- Nothing
Answer: The language and version. Naming the language and version avoids subtly wrong, version-mismatched code.
Your code throws an error. The most useful thing to give the AI is…
- The full error message and the line it happened on
- A vague 'it broke'
- A thumbs-down
- Just the filename
Answer: The full error message and the line it happened on. The exact error and line often point straight at the cause.
Which is the better request?
- 'write code'
- 'make a program'
- 'help'
- 'In Python 3.11, write a function that reads a CSV and returns total revenue per month'
Answer: 'In Python 3.11, write a function that reads a CSV and returns total revenue per month'. Language, version, and a clear goal let the model write the right thing first try.
Why include constraints like 'no new libraries'?
- To confuse the AI
- So the code fits your real environment and rules
- To make it longer
- No reason
Answer: So the code fits your real environment and rules. Constraints keep the output usable in your actual project.
What should you do BEFORE running AI-written code in production?
- Read it, test it, and ask it to explain anything unclear
- Trust it blindly
- Delete your tests
- Ship immediately
Answer: Read it, test it, and ask it to explain anything unclear. Always read, test, and understand — the AI can be confidently wrong.
The AI's code fixed one bug but broke another. You should…
- Restart with 'still broken'
- Give up
- Reply with the new precise symptom: new error and line
- Paste your whole repo
Answer: Reply with the new precise symptom: new error and line. Iterate with the exact new symptom so the model can adjust.
Pasting the FULL traceback versus describing it is…
- Worse, too long
- Better — the exact type, message, and line are gold
- The same
- Only for experts
Answer: Better — the exact type, message, and line are gold. Paste errors verbatim; never paraphrase what you could copy exactly.
How much code should you share?
- Your entire repo
- None
- Only the filename
- The smallest snippet that reproduces the issue
Answer: The smallest snippet that reproduces the issue. A minimal reproducible example removes noise and focuses the fix.
Asking the AI to 'explain what this code does' is useful because…
- It wastes time
- You learn it and can catch mistakes before shipping
- It changes nothing
- It is rude
Answer: You learn it and can catch mistakes before shipping. Understanding the code is how you avoid shipping confident errors.
Which is NOT a useful ingredient in a coding prompt?
- The goal
- The exact error
- Your zodiac sign
- Constraints and the language version
Answer: Your zodiac sign. Goal, language/version, code, error, and constraints are the useful ingredients.
Continue this course
- Previous: Controlling the Output Format
- Next: Iterating & Refining Prompts — Steer a near-miss to a great answer with precise follow-up prompts
- From the blog: Best AI Tools for Learning to Code (and How to Use Them)
Frequently asked questions
What should every 'write me code' prompt include?
The language and version (e.g. 'Python 3.11', 'JavaScript / Node 20'), the goal in one sentence, any constraints ('no new libraries', 'must handle empty input'), and — if you're fixing a bug — the smallest snippet plus the full error message. Those few facts are the difference between code that runs and code that's subtly wrong.
Should I paste the whole error or describe it?
Paste the full error and traceback verbatim, along with the relevant code. The exact exception type, message, and line number are the single most useful thing you can give a coding assistant — they often point straight at the cause, so don't paraphrase what you could copy.
Do I really need to read and test AI-written code?
Yes, always. AI can be confidently wrong — using a function that doesn't exist, mishandling an edge case, or quietly producing a subtle bug. Read it, run it, test it on real inputs, and ask the AI to explain anything you don't understand before you rely on it.
The first answer didn't fully work. Now what?
Iterate with a precise follow-up. Don't restart with 'still broken' — say exactly what happened: 'That fixed the TypeError but now it crashes on an empty file with IndexError on line 8.' Each specific correction steers the model closer.