AI tools

Free AI Python code generator

Describe what the code should do. Get complete, readable Python with type hints, error handling, and how to run it.

How it works

  1. Describe what the code should do: the input, the output, and anything that can go wrong. Mention file names, columns or API fields if you have them.
  2. Pick the kind of code (script, function, pandas job, automation or class), add constraints such as Python version or allowed libraries, and click Write my code.
  3. Copy the code, fill in any constants marked at the top, and run it on a small sample first.

Examples

Sample results for the inputs shown, so you can see the format and quality before you try it.

Example 1: input

What should the code do? Rename all .jpg files in a folder to the date they were last modified plus a counter, like 2026-09-24_001.jpg. Let me preview first.

What kind of code? Standalone script

Example 1: output
#!/usr/bin/env python3 """Rename .jpg files in a folder to YYYY-MM-DD_NNN.jpg using each file's modified date.""" import argparse from datetime import datetime from pathlib import Path def rename_photos(folder: Path, dry_run: bool = False) -> None: photos = sorted( (p for p in folder.iterdir() if p.is_file() and p.suffix.lower() in {".jpg", ".jpeg"}), key=lambda p: p.stat().st_mtime, ) counters: dict[str, int] = {} for photo in photos: day = datetime.fromtimestamp(photo.stat().st_mtime).strftime("%Y-%m-%d") counters[day] = counters.get(day, 0) + 1 target = folder / f"{day}_{counters[day]:03d}{photo.suffix.lower()}" while target.exists() and target != photo: counters[day] += 1 target = folder / f"{day}_{counters[day]:03d}{photo.suffix.lower()}" print(f"{photo.name} -> {target.name}") if not dry_run: photo.rename(target) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("folder", type=Path, help="folder that holds the photos") parser.add_argument("--dry-run", action="store_true", help="show the new names without renaming") args = parser.parse_args() rename_photos(args.folder, args.dry_run) How to run: python3 rename_photos.py ~/Pictures/trip --dry-run Check the printed names, then run it again without --dry-run. Notes: - It uses each file's modified time, not the date the camera recorded. Copied photos may carry the copy date; reading the camera date needs the Pillow library. - Needs Python 3.9 or newer.
Example 2: input

What should the code do? Read sales.csv (columns: date, region, rep, amount) and write total amount per region per month to a new CSV, sorted by region then month. Some amounts have dollar signs and commas.

What kind of code? pandas data task

Example 2: output
import pandas as pd df = pd.read_csv("sales.csv", parse_dates=["date"]) # Amounts like "$1,200.50" become 1200.5; anything unreadable becomes NaN and is reported. df["amount"] = pd.to_numeric(df["amount"].astype(str).str.replace(r"[$,]", "", regex=True), errors="coerce") bad = df["amount"].isna().sum() if bad: print(f"Warning: {bad} rows have an amount that isn't a number and were left out.") df["month"] = df["date"].dt.to_period("M").astype(str) summary = ( df.dropna(subset=["amount"]) .groupby(["region", "month"], as_index=False)["amount"].sum() .sort_values(["region", "month"]) ) summary.to_csv("sales_by_region_month.csv", index=False) print(summary.to_string(index=False)) How to run: pip install pandas python3 sales_summary.py (with sales.csv in the same folder) Notes: - Assumes the date column is in a format pandas can read, such as 2026-09-24. For day-first dates like 24/09/2026, add dayfirst=True to read_csv. - Months are written as 2026-09 so they sort correctly as text.
Example 3: input

What should the code do? A function that retries another function with exponential backoff, up to 5 tries, only on connection errors and timeouts.

What kind of code? Single function

Constraints: Standard library only

Example 3: output
import random import time from typing import Callable, TypeVar T = TypeVar("T") def retry( func: Callable[[], T], attempts: int = 5, base_delay: float = 0.5, max_delay: float = 8.0, retry_on: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError), ) -> T: """Call func until it succeeds, retrying on the given errors with exponential backoff. Waits base_delay, then twice as long each time (capped at max_delay), with jitter. Re-raises the last error if every attempt fails. """ for attempt in range(1, attempts + 1): try: return func() except retry_on: if attempt == attempts: raise delay = min(max_delay, base_delay * 2 ** (attempt - 1)) time.sleep(delay * random.uniform(0.5, 1.0)) raise AssertionError("unreachable") Example: report = retry(lambda: fetch_report(report_id)) Notes: - The requests library raises its own requests.exceptions.ConnectionError and Timeout, which are not the built-in classes. Pass them in: retry(call, retry_on=(requests.ConnectionError, requests.Timeout)). - Needs Python 3.9 or newer for the tuple[...] hint.

Tips for better results

  • Give the exact shape of your data: column names, a sample row, the file type. Code written against real names runs the first time.
  • Say what should happen with bad input. "Skip rows with no amount and tell me how many" is a decision only you can make.
  • Ask for a preview or dry-run mode for anything that renames, deletes or sends. The generator adds one when you mention it.
  • Read the Notes before you run it. They list the assumptions, such as date formats or the Python version, that most often break a first run.

FAQ

Is this Python code generator free?

Yes. Enter your email once to use it (you'll also get Something Big, our free weekly AI newsletter, and you can unsubscribe anytime). There's no account and no credit card.

Can it write pandas, API and automation code?

Yes. It writes standalone scripts, single functions, pandas data jobs, API and automation scripts using requests, and small classes. It uses the standard library unless a package like pandas is the normal tool.

Does it test the code?

No. It writes complete code with error handling and lists its assumptions, but it does not run it. Try it on a small sample of your data before relying on it.

Will it put my API key in the code?

No. It reads secrets from environment variables. Never paste real keys or passwords into the description.

More free AI tools

Related prompts

Prefer to use ChatGPT or Claude directly? These free prompts do similar jobs.

Get the best free AI tools and prompts every week

Something Big is a free AI newsletter read by 50,000+ professionals. One email a week with the AI tools and prompts that actually work, plus what changed in AI and what to do about it.