Prompts for coding: explain, generate, review, debug
Use AI as a coding partner without losing control of your code. Learn four prompt patterns (explain, generate, review, debug) with a runnable Python example for each, and the habit of always running and testing what AI gives you.
AI can explain unfamiliar code, write a first draft of a function, review your work and help find bugs. It can also produce code that looks right and fails, uses functions that do not exist, or hides a security problem. So the rule for this tutorial is: AI proposes, you verify. Every piece of code must be read, run and tested before you trust it.
You will work with one small Python example: a function that calculates the bill for a Brew & Bean order. You will explain it, generate a new function, review it, and debug a deliberately broken version.
Prerequisites: Python 3.8+ installed, a terminal, a text editor and any AI chat tool. You should know basic Python (functions, lists, dictionaries).
What makes a coding prompt work
Code answers go wrong for the same reason other answers do: missing context. For code, the context that matters is the language and version, the libraries you are using, the exact error message, the code itself and what you expected to happen. Always paste real code and real errors as text, not a description of them.
What to include
| Situation | Include |
|---|---|
| Explain code | The code, your level, what you want to understand (the whole thing or one line) |
| Generate code | Language and version, inputs and outputs with examples, libraries allowed, style rules |
| Review code | The code, what it should do, what to focus on (bugs, readability, security) |
| Debug | The code, the full error message and traceback, what you expected, what happened, what you tried |
Here is the code we will use. Save it as bill.py. It uses the Brew & Bean menu from the shared project: prices are in rupees and orders are lists of item ids with a quantity.
MENU = {
"espresso": 120,
"cappuccino": 180,
"cold-brew": 220,
"filter-coffee": 80,
"masala-chai": 90,
"croissant": 150,
"banana-bread": 130,
"veg-sandwich": 160,
}
def order_total(items):
"""Return the total in rupees for a list of {'item_id': str, 'qty': int}."""
total = 0
for line in items:
total += MENU[line["item_id"]] * line["qty"]
return total
if __name__ == "__main__":
order = [{"item_id": "cappuccino", "qty": 2}, {"item_id": "croissant", "qty": 1}]
print(order_total(order))Run it with python bill.py. It should print 510 (2 x 180 + 150).
Pattern 1: explain code
Explain the Python code below to me.
My level: [e.g. I know loops and functions but not dictionaries well].
Give me:
1. A one-sentence summary of what it does
2. A line-by-line walkthrough (group simple lines together)
3. What happens with this input: [example input]. Show the value of each variable as it changes.
4. Two things that could go wrong with unexpected input
```python
[paste code]
```What to expect: For bill.py the trace should show total going 0, 360, 510. Item 4 should mention an unknown item id (KeyError) and a negative or missing quantity.
Ask about one line or one word
You do not have to ask for the whole file. Paste the line and ask "What does MENU[line["item_id"]] do, step by step?" Small questions get precise answers. Then run a print() yourself to confirm.
Pattern 2: generate code
The most useful thing you can give a code generator is an example: one input and the exact output you want. It removes guesses about format and edge cases. Also say what you do not want (no external libraries, no global state).
Write a Python 3 function.
Name: [function name]
Purpose: [what it does]
Input: [types and meaning]
Output: [type and meaning]
Example: input [example input] gives [exact output].
Rules:
- Standard library only.
- Raise [error type] with a clear message when [bad input].
- Include a docstring and type hints.
Also write 5 tests using plain assert statements, including edge cases. Do not change anything else.What to expect: Fill it for the bill example: name order_total_with_discount, apply a 10 percent discount when the total is 500 rupees or more, and round to the nearest rupee. Then read the code before running it.
Below is one reasonable answer you might get for the discount function. Yours may look different; what matters is that it passes tests you understand. Add this to bill.py below order_total, and put the tests in a new file test_bill.py.
def order_total_with_discount(items):
"""Total in rupees; 10 percent off when the total is 500 or more."""
total = order_total(items)
if total >= 500:
total = round(total * 0.9)
return totalround returns an int when called with one argument. For 510 the result is 459.
from bill import order_total, order_total_with_discount
def test_total_basic():
order = [{"item_id": "cappuccino", "qty": 2}, {"item_id": "croissant", "qty": 1}]
assert order_total(order) == 510
def test_no_discount_below_500():
order = [{"item_id": "espresso", "qty": 2}] # 240
assert order_total_with_discount(order) == 240
def test_discount_at_500_or_more():
order = [{"item_id": "cappuccino", "qty": 2}, {"item_id": "croissant", "qty": 1}]
assert order_total_with_discount(order) == 459
def test_empty_order_is_zero():
assert order_total_with_discount([]) == 0Install pytest with pip install pytest, then run pytest in this folder.
collected 4 items
test_bill.py .... [100%]
4 passedNever paste AI code you have not run
AI can import libraries that do not exist, call functions with the wrong arguments, or use an API from an older version. If code uses a library or function you have not seen, look it up in the official documentation. Never paste code with passwords or API keys into a chat, and never run commands that delete files or change system settings until you understand each part.
Pattern 3: review code
A review prompt works best when you say what to look for and ask for a ranked list. Otherwise you get many small style comments and may miss the real problem. Ask the model to point to exact lines and to explain the risk.
Review the Python code below as a senior developer. The code is meant to [what it should do].
Focus on, in this order: 1) bugs and unhandled inputs, 2) security problems, 3) readability, 4) performance (only if it matters).
For each issue: quote the line, explain the risk in one sentence, and show a fix. Rank issues from most to least serious. If the code is fine in an area, say so. Do not rewrite the whole file.
```python
[paste code]
```What to expect: For bill.py a good review mentions: unknown item ids raise KeyError, negative or zero quantities are accepted, and prices as floats could cause rounding errors if you later use paise. Decide for yourself which to fix.
Reviews are suggestions, not orders
Models sometimes flag correct code or suggest changes that are unnecessary for your project. For each point, ask yourself: Can I reproduce the problem with an input? If you cannot, you do not need to fix it yet. Also, AI is not a replacement for real security review of anything that handles money or personal data.
Pattern 4: debug
Debugging prompts need the full error and the code that produced it. A good habit: ask for the cause first, then the fix. That way you learn why it broke, and you can judge whether the explanation fits your code. Here is a broken version. Save it as bug_demo.py and run it.
MENU = {"espresso": 120, "masala-chai": 90}
def order_total(items):
total = 0
for line in items:
total += MENU[line["item_id"]] * line["qty"]
return total
order = [{"item_id": "espresso", "qty": 1}, {"item_id": "chai", "qty": 2}]
print(order_total(order))The second item id is chai, but the menu key is masala-chai.
Traceback (most recent call last):
File "bug_demo.py", line 11, in <module>
print(order_total(order))
File "bug_demo.py", line 7, in order_total
total += MENU[line["item_id"]] * line["qty"]
KeyError: 'chai'My Python code fails. Help me find the cause before suggesting a fix.
What I expected: [expected behaviour]
What happened: [actual behaviour]
Python version: [e.g. 3.11]
What I already tried: [list, or 'nothing']
Code:
```python
[paste code]
```
Full error:
```
[paste the whole traceback]
```
Reply with: 1) the most likely cause, pointing to the line, 2) how I can confirm it myself (a print statement or a small test), 3) the smallest fix, 4) one way to prevent this kind of bug in future.What to expect: For bug_demo.py the cause is the KeyError for 'chai': the key is not in MENU. A good answer suggests printing MENU.keys(), then either correcting the id to masala-chai or checking the id and raising a clear error.
MENU = {"espresso": 120, "masala-chai": 90}
def order_total(items):
total = 0
for line in items:
item_id = line["item_id"]
if item_id not in MENU:
raise ValueError(f"Unknown item: {item_id}")
total += MENU[item_id] * line["qty"]
return total
order = [{"item_id": "espresso", "qty": 1}, {"item_id": "masala-chai", "qty": 2}]
print(order_total(order))With the corrected id it prints 300. With a wrong id it raises ValueError: Unknown item: chai, which is much clearer than a bare KeyError.
If the AI's first fix does not work, do not just say "still not working". Paste the new error or output and say what changed. If you go in circles after two or three tries, start a fresh chat with a clean summary: code, error, what you tried. Long chats full of failed attempts confuse the model.
Habits that keep you in control
Every time you use AI-written code
- I understand each line, or I asked for an explanation until I did.
- I ran it and I ran tests, including a bad input.
- I checked unfamiliar functions or libraries in the official documentation.
- No secrets (API keys, passwords, customer data) went into the prompt.
- I asked for the smallest change, not a rewrite of my whole file.
- I follow my college or employer's rules on AI-written code.
For interviews and exams
In coding interviews and many college exams you will not have AI. Use it to learn: ask for explanations, then close the chat and rewrite the solution yourself from memory. If you can't, you have not learned it yet. The skill has to stay yours.
The four-step loop for any coding task
- 1Give context: language and version, code, error, expected result.
- 2Ask for an explanation or the cause before asking for a fix.
- 3Apply the smallest change yourself.
- 4Run the code and your tests; repeat with the new output if it still fails.
Try it: Extend the bill calculator
Use the generate pattern to add a function validate_order(items) that raises ValueError for unknown item ids, missing keys, and quantities that are not positive whole numbers. Write the prompt with one example input and output. Then run your tests, add two tests for the new function, and use the review prompt on the result. Finally, deliberately break one line and practise the debug prompt with the resulting traceback.
Key takeaways
- Give code prompts the language and version, real code, the exact error and an example of expected output.
- Explain: ask for a walkthrough with a trace of variable values on a real input.
- Generate: give inputs, outputs, an example and constraints, and ask for tests.
- Review: say what to focus on and ask for a ranked list with exact lines.
- Debug: ask for the cause first, a way to confirm it, then the smallest fix.
- AI proposes, you verify: read, run and test everything, and keep secrets out of prompts.
Check yourself
Finishing the quiz marks the lesson as done.
1. Your code throws an error. Which prompt is most likely to get a correct diagnosis?
2. Why ask for tests when you ask AI to generate a function?
3. The AI suggests using a library function you have never heard of. What should you do?
4. In bill.py, what happens when an order has an item id that is not in MENU?
5. You have tried three AI fixes and the bug remains. What is a good next step?
Saved on this device. Create a free account to keep it on every device.
Practise this with Sam
A real mock interview, out loud, with an honest scorecard. Free to start.