🔨 LearnForge
AI & Tools

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.

📅 April 9, 2026 ⏱️ 20 min read ✍️ LearnForge Team 🏷️ AI tools · Real prompts · Python
Writing Python Code with AI in 2026

What AI can (and can't) do for Python automation

✅ AI is great at:
  • 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
❌ AI struggles with:
  • 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)

Best for: iterative conversation, explaining concepts, adapting existing code

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.

Typical use: "Write me a Python script that... Actually, can you also add... and change the output format to..."
🟠

Claude (Anthropic)

Best for: long scripts, complex instructions, detailed explanations

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.

Typical use: Generating a 100+ line script from a detailed spec, or getting step-by-step explanations of unfamiliar library code.
🤍

GitHub Copilot

Best for: in-editor autocomplete, writing code line-by-line faster

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.

Typical use: Writing a comment like # Sort files by extension, and Copilot generates the function body automatically.
Tool Free Tier Best For Weakness
ChatGPTYes (limited)Iteration & debuggingLong detailed specs
ClaudeYes (limited)Complex scripts & explanationsIn-editor integration
GitHub CopilotStudents onlyWriting code faster in editorNeeds 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:

Anatomy of a great Python AI prompt
1. WHAT it should do
"Write a Python script that monitors a folder for new .csv files..."
2. INPUT — what data/files/URLs it starts with
"...watching the folder /Users/me/Invoices..."
3. OUTPUT — what it should produce
"...and for each new file, send an email to admin@company.com with the file attached..."
4. LIBRARIES — what to use (or avoid)
"...using watchdog to watch the folder and smtplib to send email..."
5. CONSTRAINTS — error handling, format, Python version
"...include try/except for SMTP errors, use Python 3.11+, add logging to a file."
❌ Weak prompt

"Write a Python script to send email when a new file appears."

✅ Strong prompt

"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.

👤 User prompt
Write a Python script that organizes my Downloads folder. It should move files into subfolders based on extension: Images (jpg, png, gif, webp), Documents (pdf, doc, docx, txt), Sheets (xlsx, csv), Videos (mp4, mov, avi), Archives (zip, rar, gz). If a subfolder doesn't exist, create it. Print what it moved. Use pathlib and shutil. Python 3.10+.
🤖 AI output (Claude)
"""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).")
Result: Working script on first run. The manager runs it every Friday via a cron job — no manual sorting ever again.

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.

👤 User prompt
Write a Python script that checks a product price on a URL I give it, compares it to a target price I set, and sends me an email if the price drops below the target. Use requests and BeautifulSoup to get the price. Store the URL and target price as constants at the top. Use smtplib with Gmail. Add error handling for connection issues.
🤖 AI output (ChatGPT GPT-4o)
# 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.")
Result: Script runs every hour via cron. The only manual step: find the correct CSS selector for the price element on the target site (takes 2 minutes with browser DevTools).

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.

👤 User prompt
I have a CSV file called sales_data.csv with columns: Date, Salesperson, Region, Product, Amount. Write a Python script using pandas and openpyxl that: 1) reads the CSV, 2) calculates total sales per Salesperson and per Region, 3) writes a formatted Excel file with three sheets: Raw Data, By Salesperson, By Region. The summary sheets should have bold headers, auto-width columns, and a total row at the bottom. Save as weekly_report.xlsx.
🤖 AI output (Claude)
# 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.")
Result: Script ran on first try. Analyst saved ~2 hours every Monday, now runs it automatically via Task Scheduler before the weekly meeting.

⚙️ How People Actually Use AI for Python Day-to-Day

Beyond single-prompt code generation, there are four distinct workflows professionals use regularly:

1. Generate → Test → Refine (most common)

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.

👤 Follow-up prompt example
"This works but it crashes with KeyError: 'Price' when the CSV has an empty cell in that column. Fix it to skip rows where Price is empty and print a warning."
2. "Explain this code" — for learning and code review

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.

👤 Prompt example
"Explain this code line by line in plain English. Then tell me: what happens if the folder doesn't exist, and how would I modify it to also log moves to a file?"
3. Component-by-component for complex workflows

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.

👤 Prompt example
"I have two functions: scrape_prices() and save_to_csv(). Now write a main() function that calls them in order, adds error handling between the two steps, and logs the result. Here's the existing code: [paste code]"
4. Refactoring and improving existing code

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.

👤 Prompt example
"Refactor this script: break it into small functions with clear names, add Python type hints, add a docstring to each function, and replace the bare except with specific exception types."

🐛 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:

The perfect debugging prompt structure
1. Paste the full error message (including the traceback)
2. Paste the relevant code section
3. Describe what you expected to happen
4. Describe what is actually happening
👤 Debugging prompt example
I'm getting this error when running my price scraper:

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?
🤖 AI explains and fixes
The error happens because 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 None
return 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

🎯
AI doesn't know your specific website's structure

When generating scrapers, AI uses generic CSS selectors like [class*='price']. These often don't match the real site. Fix: open the target page, right-click the element, "Inspect", copy the actual selector, then paste it into the prompt or the code manually.

📅
AI may use outdated library versions

Libraries change — what was correct for Selenium 3 may not work in Selenium 4. If generated code throws import errors or deprecated warnings, tell AI: "This uses Selenium 4.x, update the code to use the current API." Or specify the version in your prompt upfront.

🔑
AI writes credentials into code (never do this)

AI often puts passwords and API keys directly in the code. Always move credentials to environment variables or a .env file using python-dotenv. Tell AI explicitly: "Load all credentials from environment variables, not hardcoded strings."

🧪
AI doesn't test the code it generates

AI code looks correct but may have logic errors that only appear with real data. Always run the script on a small sample first. For file operations, test on a copy of your data. For email senders, send to yourself first. Never run untested AI code on production data.

🌀
Complex multi-system integrations confuse AI

If your workflow touches 4+ systems (Salesforce + S3 + Slack + PostgreSQL), AI will generate plausible-looking code that doesn't handle the real edge cases. Break the problem into individual components, generate each one separately, test each, then combine manually.

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

Learning Path

How Long to Learn Python Automation

Week-by-week roadmap to build the Python knowledge that makes AI tools work for you.

Scripts & Examples

25 Useful Python Automation Scripts

Real copy-paste scripts — or use them as prompts to generate similar ones with AI.

Ideas & Inspiration

50 Python Automation Ideas for 2026

Pick any idea from this list and turn it into a working script with a single AI prompt.