AI Prompts for ChatGPT for Python

20 tested prompts across 4 stages. Works with ChatGPT, Claude, and Gemini.

AI Prompts for ChatGPT for Python
Scroll to explore

Getting ChatGPT for Python right takes more than a single prompt. This 4-stage guide covers Foundation: Writing Clean Python Code, Automation: Scripts and File Handling, Debugging: Finding and Fixing Problems, and more, breaking the whole process into focused steps where each prompt builds on the last. Write cleaner Python code, debug faster, automate repetitive tasks, and learn advanced patterns using ChatGPT prompts designed for Python developers at every level. Every prompt is tested and runs in ChatGPT, Claude, and Gemini.

Stage 1

Foundation: Writing Clean Python Code

Python's philosophy is readability. The best ChatGPT Python prompts produce code that is idiomatic, well-structured, and matches Python conventions rather than translating patterns from other languages.

Pythonic Rewrite

Rewrite this Python code to be more idiomatic and Pythonic: [PASTE YOUR CODE]. Specifically: replace manual loops with list comprehensions or generator expressions where appropriate, use built-in functions instead of custom implementations, apply context managers for resource management, use f-strings for string formatting, and leverage Python's standard library where I am reinventing the wheel. Explain each change you made and why it is more Pythonic.

Foundation: Writing Clean Python Code

Function Design

Write a Python function that: [DESCRIBE WHAT THE FUNCTION SHOULD DO]. Requirements: (1) clear, descriptive name following PEP 8 conventions, (2) type hints for all parameters and return value, (3) docstring with description, Args, Returns, and Raises sections, (4) handle edge cases: [LIST ANY EDGE CASES LIKE EMPTY INPUT, NONE VALUES, WRONG TYPES], (5) raise specific exceptions rather than returning None on failure, (6) include 3 example calls in the docstring showing expected behavior. Target Python 3.10+.

Foundation: Writing Clean Python Code

Data Class Design

Design a Python dataclass for [DESCRIBE THE DATA ENTITY: WHAT IT REPRESENTS, WHAT FIELDS IT NEEDS]. Use: @dataclass with appropriate configuration, field() for complex defaults, __post_init__ for validation logic, proper type hints including Optional and Union where needed, and any relevant dunder methods (__str__, __repr__, __eq__). Also show how to use dataclasses.asdict() and from_dict() patterns for serialization. Explain any design decisions.

Foundation: Writing Clean Python Code

Context Manager

Write a Python context manager for [DESCRIBE THE RESOURCE OR OPERATION: E.G., DATABASE CONNECTION, TEMPORARY DIRECTORY, TIMER, LOCK]. Implement both the class-based (__enter__/__exit__) version and the @contextmanager decorator version. Include: proper exception handling in __exit__, any cleanup logic that must always run, type hints, and a usage example showing both the with statement and nested with statements. Explain when to use each implementation approach.

Foundation: Writing Clean Python Code

Generator Pattern

Write a Python generator function to [DESCRIBE THE TASK: E.G., PROCESS LARGE FILES LINE BY LINE, YIELD BATCHES FROM A LARGE DATASET, GENERATE PAGINATED API RESULTS]. Explain why a generator is the right choice here (memory efficiency, lazy evaluation). Include: the generator function with type hints using Generator or Iterator, a consumer example using for loop and next(), send() usage if applicable, and how to handle StopIteration and cleanup. Add memory usage comparison between this approach and loading everything into a list.

Foundation: Writing Clean Python Code

Stage 2

Automation: Scripts and File Handling

Python's biggest real-world value for most users is automating repetitive tasks. These prompts cover the most common file, API, and workflow automation patterns.

File Processing Script

Write a Python script to [DESCRIBE FILE PROCESSING TASK: E.G., RENAME ALL FILES IN A DIRECTORY MATCHING A PATTERN, MERGE ALL CSVS IN A FOLDER, FIND AND REPLACE TEXT ACROSS MULTIPLE FILES]. Requirements: (1) use pathlib for all file operations (not os.path), (2) handle errors gracefully (file not found, permission errors), (3) add a --dry-run flag that shows what would happen without doing it, (4) log operations to a log file, (5) handle edge cases like already-existing output files. Include argparse for CLI arguments.

Automation: Scripts and File Handling

CSV Data Processing

Write a Python script to process a CSV file and accomplish this task: [DESCRIBE: FILTER ROWS BY CONDITION, AGGREGATE COLUMNS, JOIN WITH ANOTHER CSV, TRANSFORM VALUES, DEDUPLICATE]. Use pandas for data manipulation. Include: reading the CSV with appropriate dtype specification, the transformation logic with comments explaining each step, data validation before processing (check for expected columns, handle NaN values), writing the result to a new CSV, and a summary report printed to console showing rows in/out and any rows dropped. Add error handling for malformed input.

Automation: Scripts and File Handling

API Client Script

Write a Python script to interact with [DESCRIBE THE API: REST API, ENDPOINT, WHAT DATA I NEED TO FETCH OR SEND]. Include: (1) a requests Session with proper headers, timeout, and retry logic using urllib3 Retry, (2) API key or auth handling loaded from environment variable (not hardcoded), (3) rate limit handling with exponential backoff, (4) response validation and error handling for 4xx and 5xx responses, (5) pagination handling if the API paginates results, (6) the main data extraction and storage logic. Type hints throughout.

Automation: Scripts and File Handling

Scheduled Task / Cron Script

Write a Python script for a scheduled/cron job that [DESCRIBE THE TASK: E.G., CHECKS A DATABASE AND SENDS ALERTS, DOWNLOADS DAILY DATA FILES, CLEANS UP OLD LOGS, GENERATES A DAILY REPORT]. The script should be production-ready: (1) idempotent (safe to run multiple times), (2) proper logging with timestamps and log levels (not print statements), (3) send an alert email or webhook notification on failure, (4) write a lock file or check to prevent overlapping runs, (5) configurable via environment variables or a config file, not hardcoded values. Add a main guard.

Automation: Scripts and File Handling

Web Scraper

Write a Python web scraper to extract [DESCRIBE WHAT YOU NEED TO SCRAPE: URLS, PRODUCT DATA, ARTICLE CONTENT] from [DESCRIBE THE SITE TYPE AND STRUCTURE]. Use: requests + BeautifulSoup for static pages or Playwright for dynamic/JS-rendered pages (specify which I need). Include: (1) respectful scraping (respect robots.txt, add User-Agent header, add delays between requests), (2) extraction of [LIST SPECIFIC FIELDS], (3) storage to CSV or JSON, (4) error handling for network failures and missing elements, (5) pagination or depth handling if needed. Highlight any legal or ethical considerations.

Automation: Scripts and File Handling

Stage 3

Debugging: Finding and Fixing Problems

ChatGPT is a powerful debugging partner when you give it the right context: the error, the code, and what you expected to happen.

Error Diagnosis

I am getting this Python error: [PASTE THE FULL TRACEBACK]. The code that caused it: [PASTE THE RELEVANT CODE]. What I was trying to do: [DESCRIBE THE EXPECTED BEHAVIOR]. Please: (1) explain in plain English what this error means and why it occurred, (2) identify the exact line or logic that caused it, (3) provide the fixed version of the code, (4) explain what I need to understand to avoid this class of error in the future, (5) note if there are any other similar bugs in the surrounding code I should address.

Debugging: Finding and Fixing Problems

Logic Bug Hunt

My Python code is not working as expected. Here is the code: [PASTE CODE]. What it should do: [DESCRIBE EXPECTED BEHAVIOR]. What it actually does: [DESCRIBE ACTUAL BEHAVIOR INCLUDING ANY SAMPLE INPUT/OUTPUT]. Walk me through the code execution step by step, identify where the logic diverges from my intention, provide the corrected code, and add at least 3 assertions or test cases I should have written that would have caught this bug.

Debugging: Finding and Fixing Problems

Performance Profiling

My Python code is running too slowly. Here is the code: [PASTE CODE]. What it does: [DESCRIBE]. Sample data characteristics: [DESCRIBE INPUT SIZE AND SHAPE]. Profile this code and identify: (1) which operations are likely the bottleneck, (2) specific optimizations for each bottleneck (vectorization, caching, algorithm change, parallelism), (3) the rewritten optimized version with the changes applied, and (4) how to actually measure the improvement using timeit or cProfile. Estimate the expected speedup for each optimization.

Debugging: Finding and Fixing Problems

Type Error Deep Dive

I am getting this TypeError/TypeError-related issue in Python: [DESCRIBE THE ERROR AND PASTE THE TRACEBACK]. Relevant code: [PASTE]. My type hints: [PASTE IF ANY]. Diagnose: (1) what types are actually being passed vs. what is expected, (2) where in the call chain the type mismatch originates, (3) how to fix it properly (not just casting), (4) whether I should use Union, Optional, Protocol, or a TypeVar, and (5) how to use mypy or pyright to catch this class of error at static analysis time rather than runtime.

Debugging: Finding and Fixing Problems

Memory Leak Investigation

I suspect my Python application has a memory leak. It is doing: [DESCRIBE WHAT THE PROGRAM DOES, HOW LONG IT RUNS, WHAT DATA IT PROCESSES]. Here is the relevant code: [PASTE]. Help me: (1) identify likely sources of memory leaks in this code (unclosed resources, circular references, growing caches, generators not exhausted), (2) explain how to use tracemalloc to instrument and locate the leak, (3) provide the fixed code with proper resource cleanup, and (4) suggest how to set up memory monitoring to detect regressions.

Debugging: Finding and Fixing Problems

Stage 4

Advanced: Testing, Packaging, and Architecture

Professional Python development goes beyond writing functions that work. These prompts help with testing, packaging, and structuring larger Python projects.

Pytest Test Suite

Write a pytest test suite for this Python function/class: [PASTE CODE]. The test suite should include: (1) happy path tests with representative inputs, (2) edge case tests (empty input, None, boundary values, large input), (3) error case tests verifying correct exceptions are raised, (4) parametrize tests for multiple similar input/output pairs, (5) any necessary fixtures with appropriate scope, and (6) mocking of external dependencies (file system, network, database) using pytest-mock or unittest.mock. Target 90%+ code coverage of the provided code.

Advanced: Testing, Packaging, and Architecture

Package Structure Setup

Set up a production-ready Python package structure for a package called [PACKAGE NAME] that does [DESCRIBE PURPOSE]. Provide: (1) the recommended directory structure (layout), (2) pyproject.toml with correct metadata, dependencies, build system (setuptools), and optional dev dependencies, (3) a minimal __init__.py with version and public API exports, (4) a basic README.md outline, (5) a .gitignore appropriate for Python, and (6) GitHub Actions CI workflow that runs tests and type checking on push. Explain each configuration choice.

Advanced: Testing, Packaging, and Architecture

Async Conversion

Convert this synchronous Python code to async/await: [PASTE SYNCHRONOUS CODE]. The code currently does: [DESCRIBE: FILE I/O, HTTP REQUESTS, DATABASE QUERIES]. Use asyncio and aiohttp/aiofiles/asyncpg (as appropriate). Include: (1) async def versions of all functions, (2) proper use of await, (3) async context managers where applicable, (4) asyncio.gather() or TaskGroup for concurrent operations, (5) an async main() entry point, and (6) a comparison explaining what operations are now running concurrently and what the expected performance improvement is. Highlight any gotchas in the conversion.

Advanced: Testing, Packaging, and Architecture

Design Pattern Application

Refactor this Python code to apply the [DESCRIBE PATTERN: REPOSITORY PATTERN / STRATEGY PATTERN / OBSERVER PATTERN / FACTORY PATTERN] design pattern. Current code: [PASTE]. Problem the refactor solves: [DESCRIBE: TIGHT COUPLING, HARD TO TEST, HARD TO EXTEND]. Provide: (1) the refactored code with the pattern applied, (2) an explanation of how the pattern solves the original problem, (3) an example of adding a new implementation without changing existing code, (4) any trade-offs or complexity costs introduced by the pattern, and (5) when you would NOT use this pattern for code like this.

Advanced: Testing, Packaging, and Architecture

Dependency Injection Setup

Implement dependency injection for this Python application: [PASTE CODE OR DESCRIBE THE ARCHITECTURE: SERVICES, REPOSITORIES, EXTERNAL CLIENTS]. Current problem: the code instantiates dependencies directly, making it hard to test and configure. Implement: (1) dependency injection using either constructor injection or a DI container (like dependency-injector library), (2) interfaces using Python abstract base classes or Protocol, (3) mock implementations for testing, (4) a factory or container that wires everything together, and (5) show how the test setup is simplified. Explain the trade-off between simplicity and full DI framework complexity.

Advanced: Testing, Packaging, and Architecture

Frequently asked questions

How do I use ChatGPT to learn Python faster?+

Use it as an interactive tutor. Ask it to explain any concept in plain English, show you multiple examples of the same pattern, compare Python approaches to approaches you know from another language, and walk through code execution step by step. After it writes code, ask "why did you choose this approach instead of X?" to deepen your understanding of Python idioms.

Can ChatGPT write production-quality Python?+

ChatGPT can write solid, functional Python but you should always review output for: correctness with your actual data types and edge cases, alignment with your project's conventions, security issues (never paste secrets, always load from environment variables), and performance at your actual data scale. Treat it as a senior developer's first draft, not finished code to ship without review.

How do I give ChatGPT better context for Python debugging?+

Always provide: the full traceback (not just the error message), the relevant code (not the entire file), what you expected to happen, and a sample of the input data if relevant. The more specific you are, the more precise the diagnosis. Vague prompts like "my code doesn't work" produce vague answers.

Is ChatGPT good at Python for data science?+

Yes, especially for pandas, numpy, and matplotlib. Provide your DataFrame schema or a sample with df.head() output. For complex data transformations, show the input data structure and desired output format. For visualization, describe what you want to show and who the audience is. ChatGPT generates working code for most standard data science tasks but verify statistical logic independently for analysis that will inform decisions.

How do I use ChatGPT to improve code I have already written?+

Use the "Pythonic Rewrite" prompt with specific improvement goals: readability, performance, testability, or error handling. Ask for a code review that focuses on a specific concern rather than general feedback, which tends to produce more actionable output. Follow up by asking it to explain why each suggestion is an improvement.