Explain this code line by line
Learn
Explain what this [language] code does, as if I'm a beginner. First a 2-sentence summary, then go through it section by section. Point out anything risky, confusing or outdated.
[paste code]
See example output
Filled in with A short Python function that removes duplicate emails
Summary: this function takes a list of email addresses and returns a new list with duplicates removed, ignoring capital letters. It keeps the original order.
def unique_emails(emails):
seen = set() # remembers emails we've already kept
result = []
for e in emails:
key = e.strip().lower() # " A@x.com" and "a@x.com" count as the same
if key not in seen:
seen.add(key)
result.append(e)
return result
Watch out: it returns the original spelling of the first copy, so “A@X.com” may survive instead of “a@x.com”. If you want clean output, append key instead of e.
Example only. Your answer will differ depending on your details and the AI tool.
Debug an error
Debug
I'm getting this error:
[paste full error message]
Here's the relevant code:
[paste code]
What I expected: [expected behaviour]. What happens: [actual behaviour]. Environment: [language version, framework, OS].
Explain the most likely cause, show the fix, and tell me how to check it worked. If there are several possible causes, rank them.
See example output
Filled in with TypeError: Cannot read properties of undefined (reading 'map') in a React component
Most likely cause (90%)
products is undefined on the first render, because the data hasn’t loaded from the API yet, so products.map() crashes.
Fix
const [products, setProducts] = useState([]); // start with an empty array
...
{products?.map(p => <Card key={p.id} {...p} />)}
Check it worked: reload the page with the Network tab throttled to “Slow 3G”. The page should show an empty list first, then the products, with no red error.
Other possible causes
- The API returns
{ data: [...] }, so you need response.data, not response
- A typo in the prop name passed from the parent component
Example only. Your answer will differ depending on your details and the AI tool.
Write a small script for a job
Build
Write a [Python / JavaScript / Google Apps Script] script that [task, e.g. "renames all images in a folder using the date they were taken"].
I'm not a developer, so: explain how to install anything needed, how to run it step by step, add comments in the code, and make it safe (e.g. don't delete or overwrite files without asking).
See example output
Filled in with Rename all photos in a folder by the date they were taken (Python, non-developer)
Step 1: install Python from python.org (tick “Add Python to PATH” during setup).
Step 2: open Command Prompt and run: pip install pillow
Step 3: save the code below as rename_photos.py in the photos folder.
from pathlib import Path
from PIL import Image
folder = Path(__file__).parent
for photo in folder.glob("*.jpg"):
date = Image.open(photo).getexif().get(306) # 306 = "date taken"
if not date:
print("No date found, skipping:", photo.name)
continue
new_name = date.replace(":", "-").replace(" ", "_") + ".jpg"
target = folder / new_name
if target.exists():
print("Already exists, skipping:", new_name) # never overwrites
continue
photo.rename(target)
print(photo.name, "→", new_name)
Step 4: double-click the file, or run python rename_photos.py. Test on a copy of the folder first!
Example only. Your answer will differ depending on your details and the AI tool.
Refactor for readability
Improve
Refactor this code to make it easier to read and maintain without changing what it does:
[paste code]
Use clearer names, split long functions, remove duplication, and follow common [language] conventions. Show the new code, then list each change and why.
See example output
Filled in with A 60-line JavaScript function that calculates an order total
const TAX_RATE = 0.18;
const FREE_SHIPPING_ABOVE = 999;
function subtotal(items) {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
function shippingFee(amount) {
return amount >= FREE_SHIPPING_ABOVE ? 0 : 49;
}
function orderTotal(items, coupon) {
const beforeDiscount = subtotal(items);
const afterDiscount = applyCoupon(beforeDiscount, coupon);
return afterDiscount * (1 + TAX_RATE) + shippingFee(afterDiscount);
}
What changed
- Split one long function into 4 small ones with clear names
- Replaced magic numbers (0.18, 999) with named constants
- Removed a duplicated loop that calculated the subtotal twice
Example only. Your answer will differ depending on your details and the AI tool.
Write unit tests
Test
Write unit tests for this function using [testing framework]:
[paste function]
Cover the normal cases, edge cases (empty input, very large values, wrong types) and error cases. Name each test so it describes what it checks.
See example output
Filled in with A Python function calculate_discount(price, percent)
import pytest
from shop import calculate_discount
def test_applies_10_percent_discount():
assert calculate_discount(1000, 10) == 900
def test_zero_percent_returns_original_price():
assert calculate_discount(500, 0) == 500
def test_100_percent_makes_it_free():
assert calculate_discount(500, 100) == 0
def test_rounds_to_two_decimal_places():
assert calculate_discount(99.99, 15) == 84.99
def test_negative_percent_raises_error():
with pytest.raises(ValueError):
calculate_discount(500, -5)
def test_text_instead_of_number_raises_error():
with pytest.raises(TypeError):
calculate_discount("500", 10)
Example only. Your answer will differ depending on your details and the AI tool.
Review my code like a senior developer
Improve
Review this [language] code as a senior developer would in a pull request:
[paste code]
Comment on: bugs, security issues, performance, readability and missing error handling. Rank issues as must-fix, should-fix or nice-to-have. Be direct.
See example output
Filled in with A PHP contact-form handler
Must-fix
- SQL injection (line 14).
"... WHERE email = '$email'" puts user input straight into the query. Use prepared statements.
- No CSRF protection. Anyone can submit this form from another site.
Should-fix
- Email validation only checks for “@”. Use
filter_var($email, FILTER_VALIDATE_EMAIL).
- Errors are shown to the user with
die(mysqli_error()), which leaks database details.
Nice-to-have
- Move the database password to an environment variable.
- Rename
$x and $data2 to say what they hold.
Example only. Your answer will differ depending on your details and the AI tool.
Excel or Google Sheets formula
Build
In [Excel / Google Sheets], my data is set up like this: [describe columns, e.g. "A = order date, B = customer, C = amount"].
I want a formula that [what you want, e.g. "totals the amount per customer for the current month only"]. Give the formula, explain how it works, and tell me which cell to put it in.
See example output
Filled in with Google Sheets: A = order date, B = customer, C = amount; total per customer for this month
Put this in F2, with the customer name in E2:
=SUMIFS(C:C, B:B, E2, A:A, ">="&EOMONTH(TODAY(),-1)+1, A:A, "<="&EOMONTH(TODAY(),0))
How it works
SUMIFS adds up column C only where every condition is true
B:B, E2: the customer matches the name in E2
EOMONTH(TODAY(),-1)+1 is the 1st of this month
EOMONTH(TODAY(),0) is the last day of this month
Drag F2 down to fill it for every customer in column E.
Example only. Your answer will differ depending on your details and the AI tool.
Plan a small app before coding
Build
I want to build [app idea] for [users]. Main features: [list].
Before writing code, plan it: suggest a simple tech stack for a beginner, the data I need to store, the screens/pages, and a step-by-step build order where each step gives me something working. Flag anything that's harder than it sounds.
See example output
Filled in with A booking app for a yoga studio with 3 teachers
Simple stack for a beginner: Next.js + Supabase (database and login) + Vercel (free hosting)
Data to store: classes (time, teacher, capacity) · bookings (user, class, status) · users (name, phone)
Screens: class timetable · class details + “Book” button · my bookings · admin: add/edit classes
Build order (each step works on its own)
- Static timetable page with fake data
- Real classes from the database
- Login with phone number
- Booking a class (and stopping when it’s full)
- “My bookings” + cancel
- Admin page for teachers
Harder than it sounds: handling two people booking the last spot at the same time, and sending WhatsApp reminders (needs a paid API).
Example only. Your answer will differ depending on your details and the AI tool.
Convert code to another language
Build
Convert this [source language] code to [target language]:
[paste code]
Use idiomatic [target language], not a line-by-line translation. Point out any behaviour that changes between the two languages, and list any libraries I need to install.
See example output
Filled in with A Python CSV-reading script converted to JavaScript (Node.js)
import { readFile } from "node:fs/promises";
import { parse } from "csv-parse/sync";
const text = await readFile("orders.csv", "utf8");
const rows = parse(text, { columns: true, skip_empty_lines: true });
const total = rows.reduce((sum, row) => sum + Number(row.amount), 0);
console.log(`Total: ₹${total.toFixed(2)}`);
Install: npm install csv-parse
Behaviour differences
- Python’s
csv.DictReader returns text; so does csv-parse, so Number() is needed before adding
- Top-level
await needs "type": "module" in package.json
Example only. Your answer will differ depending on your details and the AI tool.
Getting better results
Paste the full error. The complete error message and the code around it are worth more than any description.
Say your level. “I’m not a developer” changes the answer completely. You get install steps, comments and safety checks.
Run it somewhere safe first. Test scripts on copies of your files, and review AI code before it touches anything important.