Best ChatGPT Prompt for Python Code
Write, debug, and understand Python scripts — for automation, data analysis, web scraping, and more.
The Prompt
You are a senior Python developer with 15 years of experience. Help me with a Python task. What I'm trying to do: [DESCRIBE THE GOAL IN PLAIN ENGLISH] Python version: [3.10 / 3.11 / 3.12 / don't know] Libraries allowed: [list any restrictions, or 'anything on PyPI'] My current code (if any): ```python [PASTE YOUR CODE] ``` The problem: [what's not working, or what needs to be built] Expected input format: [what the script receives] Expected output format: [what the script should produce] My skill level: [beginner / intermediate / advanced] Requirements: - Write clean, Pythonic code (follow PEP 8) - Use type hints for function signatures - Add docstrings for functions - Include error handling for edge cases (empty input, missing files, network errors) - Show an example of running the code with sample input - If there's a simpler/more efficient approach, mention it - Use the standard library when possible — only pull in pip packages when necessary
How to Use This Prompt
- Describe what the script should do end-to-end, not just the next step
- Paste error messages fully — the AI can usually diagnose from the traceback
- For data scripts, paste 2-3 sample rows of your real data
- For automation scripts, describe what you currently do manually step by step
Example Output
Task: Read a CSV of transactions and produce a monthly summary
import csv
from collections import defaultdict
from datetime import datetime
def summarize_by_month(csv_path: str) -> dict[str, float]:
"""Sum transaction amounts by YYYY-MM month."""
totals: dict[str, float] = defaultdict(float)
with open(csv_path, newline='') as f:
reader = csv.DictReader(f)
for row in reader:
date = datetime.strptime(row['date'], '%Y-%m-%d')
key = date.strftime('%Y-%m')
totals[key] += float(row['amount'])
return dict(sorted(totals.items()))
if __name__ == '__main__':
summary = summarize_by_month('transactions.csv')
for month, total in summary.items():
print(f"{month}: ${total:,.2f}")Tips to Get Better Results
- Ask for tests. Say 'Write pytest tests for this function' to catch bugs early.
- Explain before rewriting. For code you don't understand, say 'Explain this script line by line.'
- Compare approaches. Ask 'Is there a pandas way and a vanilla Python way? Show me both with tradeoffs.'
- Small scripts. For one-off tasks, say 'Write the shortest Python that does this, no error handling' — save yourself time.