How to Write Python Code with AI: Real Examples & Prompts 2026
ChatGPT, Claude, GitHub Copilot — AI tools have completely changed how people write Python automation. Here's how developers actually use them: the exact prompts, the real workflows, and how to get code that works on the first run.
What AI can (and can't) do for Python automation
- Generating boilerplate code in seconds
- Explaining what a script does line by line
- Suggesting the right library for a task
- Refactoring messy or repetitive code
- Debugging error messages you don't understand
- Translating plain English into working code
- Code that touches your specific local files
- Sites with anti-scraping protection
- Complex multi-system integrations
- Testing the code it generates
- Knowing your business logic precisely
- Keeping up with very recent library changes
🤖 Which AI Tool to Use for Python in 2026
Three tools dominate Python AI coding in 2026. Each has a different strength — most experienced developers use all three depending on the task.
ChatGPT (GPT-4o)
The most widely used AI coding tool. Excellent for back-and-forth conversations where you refine code through multiple requests. Good at taking your vague description and asking clarifying questions before generating. The free version is usable; GPT-4o produces significantly better code.
Claude (Anthropic)
Particularly strong at following detailed, multi-step instructions precisely. If you give Claude a long, specific prompt with many requirements, it tends to honour all of them without dropping conditions. Also excellent at explaining its own code in plain English — ideal for learners.
GitHub Copilot
Lives directly inside VS Code (and other editors). As you type, it predicts the next line or block and suggests a completion. You press Tab to accept. Unlike chat tools, you don't switch windows — it's integrated into your actual workflow. Best for developers who already know Python and want to write faster.
# Sort files by extension, and Copilot generates the function body automatically.
| Tool | Free Tier | Best For | Weakness |
|---|---|---|---|
| ChatGPT | Yes (limited) | Iteration & debugging | Long detailed specs |
| Claude | Yes (limited) | Complex scripts & explanations | In-editor integration |
| GitHub Copilot | Students only | Writing code faster in editor | Needs Python knowledge |
📝 The Perfect Prompt Formula for Python Code
The quality of AI-generated code depends almost entirely on the quality of your prompt. Vague prompt → generic code. Specific prompt → production-ready code. Here's the formula that consistently works:
"Write a Python script to send email when a new file appears."
"Write a Python 3.11 script using watchdog to monitor /Users/me/Invoices for new .csv files. When one appears, send it as an email attachment to admin@co.com via Gmail SMTP (credentials from env vars). Add try/except for SMTP errors and log events to app.log."
💡 Real Prompt + Code Examples
These are real prompts people use daily, with the actual code AI generates. Each example shows the prompt → output flow.
Example 1 — File Organizer
A marketing manager who downloads hundreds of assets per week uses this to clean up Downloads automatically.
"""Auto-organise Downloads by file extension."""
import shutil
from pathlib import Path
DOWNLOADS = Path.home() / "Downloads"
CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".webp", ".heic"],
"Documents": [".pdf", ".doc", ".docx", ".txt", ".pages", ".md"],
"Sheets": [".xlsx", ".xls", ".csv", ".numbers"],
"Videos": [".mp4", ".mov", ".avi", ".mkv", ".wmv"],
"Archives": [".zip", ".rar", ".gz", ".tar", ".7z"],
}
def get_category(suffix: str) -> str:
suffix = suffix.lower()
for cat, exts in CATEGORIES.items():
if suffix in exts:
return cat
return "Other"
moved = 0
for file in DOWNLOADS.iterdir():
if file.is_dir():
continue
dest_dir = DOWNLOADS / get_category(file.suffix)
dest_dir.mkdir(exist_ok=True)
shutil.move(str(file), str(dest_dir / file.name))
print(f"✅ {file.name} → {dest_dir.name}/")
moved += 1
print(f"\nDone. Moved {moved} file(s).")
Example 2 — Price Monitor with Email Alert
A freelance buyer uses this to track equipment prices and get notified when they drop below a target.
# pip install requests beautifulsoup4
import smtplib, requests
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
PRODUCT_URL = "https://example.com/product"
TARGET_PRICE = 199.99
EMAIL_FROM = "you@gmail.com"
EMAIL_TO = "you@gmail.com"
APP_PASSWORD = "your_app_password" # Gmail App Password
def get_price(url: str) -> float | None:
try:
headers = {"User-Agent": "Mozilla/5.0"}
r = requests.get(url, headers=headers, timeout=10)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")
# Adjust selector to match the site's price element:
price_tag = soup.select_one("[class*='price']")
if price_tag:
raw = price_tag.get_text(strip=True).replace("$", "").replace(",", "")
return float(raw)
except Exception as e:
print(f"Error fetching price: {e}")
return None
def send_alert(price: float) -> None:
body = f"Price dropped to ${price:.2f}! (Target: ${TARGET_PRICE})\n{PRODUCT_URL}"
msg = MIMEText(body)
msg["Subject"] = f"🔔 Price Alert: ${price:.2f}"
msg["From"] = EMAIL_FROM
msg["To"] = EMAIL_TO
try:
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(EMAIL_FROM, APP_PASSWORD)
server.send_message(msg)
print("✅ Alert email sent!")
except smtplib.SMTPException as e:
print(f"SMTP error: {e}")
price = get_price(PRODUCT_URL)
if price is not None:
print(f"Current price: ${price:.2f}")
if price < TARGET_PRICE:
send_alert(price)
else:
print("Price not low enough yet.")
Example 3 — Excel Report from CSV Data
A sales ops analyst replaced 2 hours of weekly manual work with this script — one prompt to ChatGPT, five minutes of testing.
# pip install pandas openpyxl
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.utils import get_column_letter
df = pd.read_csv("sales_data.csv")
by_person = df.groupby("Salesperson")["Amount"].sum().reset_index()
by_region = df.groupby("Region")["Amount"].sum().reset_index()
# Append totals row
by_person.loc[len(by_person)] = ["TOTAL", by_person["Amount"].sum()]
by_region.loc[len(by_region)] = ["TOTAL", by_region["Amount"].sum()]
with pd.ExcelWriter("weekly_report.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="Raw Data", index=False)
by_person.to_excel(writer, sheet_name="By Salesperson", index=False)
by_region.to_excel(writer, sheet_name="By Region", index=False)
def format_sheet(ws):
header_fill = PatternFill("solid", fgColor="1E40AF")
for cell in ws[1]:
cell.font = Font(bold=True, color="FFFFFF")
cell.fill = header_fill
cell.alignment = Alignment(horizontal="center")
for col in ws.columns:
max_len = max(len(str(c.value or "")) for c in col)
ws.column_dimensions[get_column_letter(col[0].column)].width = max_len + 4
wb = load_workbook("weekly_report.xlsx")
for sheet_name in wb.sheetnames:
format_sheet(wb[sheet_name])
wb.save("weekly_report.xlsx")
print("✅ weekly_report.xlsx created.")
⚙️ How People Actually Use AI for Python Day-to-Day
Beyond single-prompt code generation, there are four distinct workflows professionals use regularly:
Generate the full script in one prompt. Run it. If something is wrong or missing, paste the error or describe what needs changing back into the chat. Repeat 2–3 times until the script does exactly what you need. This loop is fast — most scripts are done in under 15 minutes.
Paste code you found (Stack Overflow, GitHub, a colleague's script) and ask AI to explain it line by line. Then ask "what would happen if I change X to Y?" This is how many developers learn new libraries 3x faster than reading documentation.
For multi-step automation (e.g., scrape → clean → store → email), generate each component separately. Then ask AI to combine them. This produces cleaner code than trying to generate the whole thing at once, and makes debugging much easier when one component fails.
Paste a working but messy script and ask AI to refactor it: add type hints, break it into functions, add docstrings, or improve error handling. This is one of AI's strongest use cases — it never gets tired of cleaning up code.
🐛 Using AI to Debug Python Errors
AI is exceptionally good at debugging Python errors — often better than Stack Overflow because it understands the context of your specific code. The trick is to give AI enough information:
AttributeError: 'NoneType' object has no attribute 'get_text' File "scraper.py", line 14, in get_price price_tag.get_text(strip=True)
Here's my code: [paste]. The script should scrape a price from the page, but sometimes the element isn't there. How do I fix this so it handles the case where the price element doesn't exist?
soup.select_one() returns None when the element isn't found on the page, and you're calling .get_text() on None. Fix: add a None check before calling get_text:
price_tag = soup.select_one("[class*='price']")if price_tag is None: print("Price element not found on page") return Nonereturn float(price_tag.get_text(strip=True).replace("$", "").replace(",", ""))
This is a common scraping issue — the element selector might not match if the site changes its HTML or if you hit a CAPTCHA page. You can verify by printing
r.text[:500] to see what HTML you actually received.⚠️ AI Limitations & How to Work Around Them
Learn Python to Use AI Tools Better
AI generates code faster when you know enough Python to give it precise prompts — and to fix what it gets wrong. Our course gives you that foundation: practical automation skills in weeks, not years.
Try a Free Lesson →Frequently Asked Questions
Can AI write Python automation code for me?
Yes — for most common automation tasks (files, email, Excel, web scraping, scheduling), AI generates complete, working scripts from a plain-English description. Complex multi-system integrations require more iteration and human oversight. Even experienced developers use AI to skip boilerplate and discover the right library for a task faster.
What is the best AI tool for writing Python code in 2026?
GitHub Copilot is best for in-editor autocomplete while writing code. Claude is best for generating long, complex scripts from detailed instructions. ChatGPT (GPT-4o) is best for iterative conversation, debugging, and adapting existing code. Most developers use all three depending on the task — they complement each other well.
How do I prompt AI to write Python code correctly?
Include five things: (1) what the script should do, (2) the input source (file path, URL, API), (3) the expected output (file type, email, terminal print), (4) which libraries to use, and (5) error handling requirements and Python version. The more specific your prompt, the closer the first output is to what you need.
Do I need to know Python to use AI for coding?
You need basic Python knowledge to use AI effectively — enough to understand what generated code does, run it, and make small edits. Without any Python, you won't know when the AI output is wrong or how to fix errors. A good model: AI generates 80% of the code, your Python knowledge handles the remaining 20%. Learning Python basics (1–2 months) makes AI tools dramatically more powerful.
Related Articles
How Long to Learn Python Automation
Week-by-week roadmap to build the Python knowledge that makes AI tools work for you.
25 Useful Python Automation Scripts
Real copy-paste scripts — or use them as prompts to generate similar ones with AI.
50 Python Automation Ideas for 2026
Pick any idea from this list and turn it into a working script with a single AI prompt.