Introduction
Python remains one of the most versatile programming languages in 2026, powering everything from automation scripts to high-performance APIs. But even experienced developers spend hours on boilerplate code, debugging edge cases, and searching for the right library. This is where AI-powered code generation shines. By crafting precise prompts, you can turn natural language into production-ready Python code in seconds. Whether you're building a data pipeline, a web scraper, or a FastAPI microservice, the right prompt saves time and reduces errors. Below are 10 battle-tested prompts I use daily, organized by complexity. Each includes a real-world example and the generated code.
1. Basic Script: File Renamer
Prompt: "Write a Python script that renames all .txt files in a given directory by adding a date prefix in the format YYYY-MM-DD. Use the os and datetime modules. Include error handling for missing directories and non-existent files. The script should accept the directory path as a command-line argument via sys.argv."
Use case: Automating log file organization. Instead of manually renaming dozens of files, you run the script once.
import os
import sys
from datetime import datetime
def rename_files(directory):
if not os.path.isdir(directory):
print(f"Error: Directory '{directory}' does not exist.")
sys.exit(1)
date_prefix = datetime.now().strftime("%Y-%m-%d")
for filename in os.listdir(directory):
if filename.endswith(".txt"):
old_path = os.path.join(directory, filename)
new_name = f"{date_prefix}_{filename}"
new_path = os.path.join(directory, new_name)
try:
os.rename(old_path, new_path)
print(f"Renamed: {filename} -> {new_name}")
except OSError as e:
print(f"Error renaming {filename}: {e}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python rename.py <directory_path>")
sys.exit(1)
rename_files(sys.argv[1])
2. Data Processing: CSV Cleaner
Prompt: "Create a Python function that reads a CSV file, removes rows with missing values in any column, and writes the cleaned data to a new CSV file. Use only the csv module from the standard library. The function should accept input and output file paths as parameters. Add a progress indicator that prints the number of rows removed."
Use case: Cleaning messy datasets before analysis. This example processes a 10,000-row customer list and removes 200 incomplete entries.
import csv
def clean_csv(input_file, output_file):
with open(input_file, 'r', newline='') as infile, \
open(output_file, 'w', newline='') as outfile:
reader = csv.DictReader(infile)
fieldnames = reader.fieldnames
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
removed = 0
for row in reader:
if any(value == '' or value is None for value in row.values()):
removed += 1
else:
writer.writerow(row)
print(f"Cleaning complete. Removed {removed} rows with missing values.")
return removed
# Example usage:
# clean_csv('customers.csv', 'customers_clean.csv')
3. Web Scraping: Headline Collector
Prompt: "Write a Python script using requests and BeautifulSoup (from bs4) to scrape all article headlines from https://example.com/news (assume standard HTML structure with
). Save the headlines to a text file, one per line. Handle HTTP errors and timeouts gracefully. If the page is unreachable, print an error message and exit."
Use case: Monitoring news aggregators or competitor content. The script runs daily via cron.
import requests
from bs4 import BeautifulSoup
import sys
def scrape_headlines(url, output_file):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Failed to fetch {url}: {e}")
sys.exit(1)
soup = BeautifulSoup(response.text, 'html.parser')
headlines = [h2.get_text(strip=True) for h2 in soup.find_all('h2', class_='headline')]
with open(output_file, 'w', encoding='utf-8') as f:
for headline in headlines:
f.write(headline + '\n')
print(f"Saved {len(headlines)} headlines to {output_file}")
scrape_headlines('https://example.com/news', 'headlines.txt')
4. Automation: Bulk Image Resizer
Prompt: "Develop a Python script using Pillow (PIL) that resizes all JPEG images in a folder to a maximum width of 800 pixels while maintaining aspect ratio. Save the resized images to an output folder. Use argparse to accept input directory, output directory, and optional max width. Include logging of resized files."
Use case: Preparing images for a website to reduce load times. The script processes 500 product photos in under 30 seconds.
import argparse
import os
from PIL import Image
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def resize_images(input_dir, output_dir, max_width=800):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.lower().endswith('.jpg') or filename.lower().endswith('.jpeg'):
filepath = os.path.join(input_dir, filename)
with Image.open(filepath) as img:
if img.width > max_width:
ratio = max_width / img.width
new_size = (max_width, int(img.height * ratio))
img_resized = img.resize(new_size, Image.LANCZOS)
output_path = os.path.join(output_dir, filename)
img_resized.save(output_path, optimize=True)
logging.info(f"Resized {filename} to {new_size}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('input_dir', help='Directory with images')
parser.add_argument('output_dir', help='Directory for resized images')
parser.add_argument('--max-width', type=int, default=800, help='Max width in pixels')
args = parser.parse_args()
resize_images(args.input_dir, args.output_dir, args.max_width)
5. API Client: GitHub User Fetcher
Prompt: "Write a Python class that uses the requests library to fetch GitHub user information via the REST API (https://api.github.com/users/{username}). Include methods for getting user details (name, bio, public repos) and a list of recent public repositories. Handle rate limiting by checking the 'X-RateLimit-Remaining' header. If the limit is exceeded, wait and retry. Use type hints and docstrings."
Use case: Building a tool to analyze contributor profiles for an open-source project.
import requests
import time
from typing import Dict, List, Optional
class GitHubUserClient:
BASE_URL = "https://api.github.com"
def __init__(self, token: Optional[str] = None):
self.session = requests.Session()
if token:
self.session.headers.update({"Authorization": f"token {token}"})
def _handle_rate_limit(self, response: requests.Response) -> None:
remaining = int(response.headers.get('X-RateLimit-Remaining', 1))
if remaining == 0:
reset_time = int(response.headers.get('X-RateLimit-Reset', time.time()))
wait = reset_time - time.time() + 1
print(f"Rate limit exceeded. Waiting {wait:.0f} seconds...")
time.sleep(max(wait, 1))
def get_user(self, username: str) -> Dict:
url = f"{self.BASE_URL}/users/{username}"
response = self.session.get(url)
self._handle_rate_limit(response)
response.raise_for_status()
return response.json()
def get_repos(self, username: str) -> List[Dict]:
url = f"{self.BASE_URL}/users/{username}/repos"
response = self.session.get(url)
self._handle_rate_limit(response)
response.raise_for_status()
return response.json()
# Example:
# client = GitHubUserClient()
# user = client.get_user('octocat')
# print(user['name'])
6. FastAPI Endpoint: Simple CRUD for Notes
Prompt: "Create a FastAPI application with an in-memory SQLite database (using SQLAlchemy and aiosqlite) for managing notes. Each note has an id, title, content, and created_at timestamp. Implement endpoints: POST /notes (create), GET /notes (list all), GET /notes/{id} (get one), PUT /notes/{id} (update), DELETE /notes/{id} (delete). Use Pydantic models for request/response validation. Add CORS middleware to allow all origins."
Use case: A minimal backend for a note-taking mobile app. Deployed with Uvicorn.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from typing import List, Optional
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# SQLite setup
DATABASE_URL = "sqlite:///./notes.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class NoteModel(Base):
__tablename__ = "notes"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
content = Column(String)
created_at = Column(DateTime, default=datetime.utcnow)
Base.metadata.create_all(bind=engine)
# Pydantic schemas
class NoteCreate(BaseModel):
title: str
content: str
class NoteUpdate(BaseModel):
title: Optional[str] = None
content: Optional[str] = None
class NoteResponse(BaseModel):
id: int
title: str
content: str
created_at: datetime
class Config:
orm_mode = True
# Endpoints
@app.post("/notes", response_model=NoteResponse, status_code=201)
def create_note(note: NoteCreate):
db = SessionLocal()
db_note = NoteModel(title=note.title, content=note.content)
db.add(db_note)
db.commit()
db.refresh(db_note)
db.close()
return db_note
@app.get("/notes", response_model=List[NoteResponse])
def list_notes():
db = SessionLocal()
notes = db.query(NoteModel).all()
db.close()
return notes
@app.get("/notes/{note_id}", response_model=NoteResponse)
def get_note(note_id: int):
db = SessionLocal()
note = db.query(NoteModel).filter(NoteModel.id == note_id).first()
db.close()
if not note:
raise HTTPException(status_code=404, detail="Note not found")
return note
@app.put("/notes/{note_id}", response_model=NoteResponse)
def update_note(note_id: int, note: NoteUpdate):
db = SessionLocal()
db_note = db.query(NoteModel).filter(NoteModel.id == note_id).first()
if not db_note:
db.close()
raise HTTPException(status_code=404, detail="Note not found")
if note.title is not None:
db_note.title = note.title
if note.content is not None:
db_note.content = note.content
db.commit()
db.refresh(db_note)
db.close()
return db_note
@app.delete("/notes/{note_id}", status_code=204)
def delete_note(note_id: int):
db = SessionLocal()
db_note = db.query(NoteModel).filter(NoteModel.id == note_id).first()
if not db_note:
db.close()
raise HTTPException(status_code=404, detail="Note not found")
db.delete(db_note)
db.commit()
db.close()
7. FastAPI with Background Tasks: Email Notifier
Prompt: "Extend a FastAPI app with a background task that sends a welcome email after user registration. Use FastAPI's BackgroundTasks. The email sending is simulated with a print statement (but comment that you'd replace it with smtplib or an email API). The endpoint accepts a JSON body with email and name. Include a GET /status endpoint that returns the number of emails sent so far using an in-memory counter."
Use case: Offloading slow operations (email, logging) from request-response cycle.
from fastapi import FastAPI, BackgroundTasks, HTTPException
from pydantic import BaseModel
import time
app = FastAPI()
email_counter = 0
def send_welcome_email(email: str, name: str):
global email_counter
# Simulate sending email
time.sleep(2) # Simulate network delay
print(f"Welcome email sent to {name} at {email}")
# Real implementation would use smtplib or SendGrid API
email_counter += 1
class UserRegistration(BaseModel):
email: str
name: str
@app.post("/register")
async def register_user(user: UserRegistration, background_tasks: BackgroundTasks):
# Validate email format (simplified)
if "@" not in user.email:
raise HTTPException(status_code=400, detail="Invalid email")
# Add background task
background_tasks.add_task(send_welcome_email, user.email, user.name)
return {"message": f"User {user.name} registered. Welcome email queued."}
@app.get("/status")
def get_status():
return {"emails_sent": email_counter}
8. Async Web Scraper with aiohttp
Prompt: "Write an asynchronous Python script using aiohttp and asyncio to fetch the titles of multiple web pages concurrently. Accept a list of URLs. Use a semaphore to limit concurrent requests to 5. Return a dictionary mapping each URL to its title (extracted from
Use case: Quickly checking if multiple websites are online and have correct titles. Runs 10x faster than sequential scraper.
import asyncio
import aiohttp
from bs4 import BeautifulSoup
import time
async def fetch_title(session, url, semaphore):
async with semaphore:
try:
async with session.get(url, timeout=10) as response:
response.raise_for_status()
text = await response.text()
soup = BeautifulSoup(text, 'html.parser')
title = soup.title.string.strip() if soup.title else "No title"
return url, title
except Exception as e:
return url, f"Error: {str(e)}"
async def fetch_all_titles(urls):
semaphore = asyncio.Semaphore(5)
async with aiohttp.ClientSession() as session:
tasks = [fetch_title(session, url, semaphore) for url in urls]
results = await asyncio.gather(*tasks)
return dict(results)
if __name__ == "__main__":
urls = [
"https://example.com",
"https://httpbin.org",
"https://python.org",
"https://nonexistent.xyz"
]
start = time.time()
titles = asyncio.run(fetch_all_titles(urls))
elapsed = time.time() - start
for url, title in titles.items():
print(f"{url}: {title}")
print(f"Total time: {elapsed:.2f}s")
9. CLI Tool with Click: Password Generator
Prompt: "Build a command-line password generator using the Click library. It should accept options: --length (default 12), --numbers (include digits), --symbols (include special chars), --uppercase (include uppercase letters). Generate a random password using secrets module for cryptographically secure randomness. Print the password to stdout. Add a --help message explaining each option."
Use case: Generating strong passwords for new accounts. Can be integrated into shell scripts.
import click
import secrets
import string
@click.command()
@click.option('--length', default=12, help='Length of the password', show_default=True)
@click.option('--numbers', is_flag=True, help='Include numbers')
@click.option('--symbols', is_flag=True, help='Include special characters')
@click.option('--uppercase', is_flag=True, help='Include uppercase letters')
def generate_password(length, numbers, symbols, uppercase):
"""Generate a secure random password."""
characters = string.ascii_lowercase
if uppercase:
characters += string.ascii_uppercase
if numbers:
characters += string.digits
if symbols:
characters += string.punctuation
if not characters:
click.echo("Error: At least one character set must be selected.")
return
password = ''.join(secrets.choice(characters) for _ in range(length))
click.echo(password)
if __name__ == '__main__':
generate_password()
10. Data Visualization: Interactive Dashboard with Plotly
Prompt: "Write a Python script using Plotly Express to create an interactive line chart showing monthly sales data from a CSV file. The CSV has columns: 'month' (string), 'sales' (float), 'region' (string). Create a multi-line chart where each region is a separate line. Add hover data showing exact values. Save the chart as an HTML file. Use pandas to read the CSV."
Use case: Quick ad-hoc analysis for business stakeholders. The HTML file can be shared via email.
import pandas as pd
import plotly.express as px
def create_sales_chart(csv_path, output_html):
df = pd.read_csv(csv_path)
# Ensure month is ordered
df['month'] = pd.Categorical(df['month'], categories=[
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
], ordered=True)
fig = px.line(
df,
x='month',
y='sales',
color='region',
title='Monthly Sales by Region',
labels={'sales': 'Sales (USD)', 'month': 'Month'},
hover_data={'sales': ':,.2f'}
)
fig.write_html(output_html)
print(f"Chart saved to {output_html}")
# Example:
# create_sales_chart('sales_data.csv', 'sales_dashboard.html')
Conclusion
These 10 prompts cover a wide spectrum of Python tasks — from simple automation to async APIs. The key to effective code generation is specificity: include exact module names, error handling, and output format in your prompts. As AI models improve in 2026, they can handle even more complex logic, but the human skill of framing the problem remains crucial. Start with these templates, adapt them to your domain, and you'll cut development time by half. Bookmark this page and revisit when you need a quick script or a FastAPI endpoint — just copy, paste, and modify.
Comments