Python Coding Prompts: 30+ Templates for ChatGPT & Claude
Copy-paste Python prompts for debugging, data analysis, automation scripts, and API development. Tested with GPT-4, Claude, and Gemini.
- Debugging Prompts — Fix errors and understand stack traces
- Data Analysis Prompts — Pandas, NumPy, and visualization
- Automation Scripts — File handling, web scraping, APIs
- Best Practices — Type hints, testing, documentation
Save All 30+ Python Prompts
Free account. No credit card. Access from anywhere.
Python Debugging Prompts
Fix errors and understand what went wrong
I'm getting this Python error: ``` [PASTE YOUR ERROR/TRACEBACK HERE] ``` My code: ```python [PASTE YOUR CODE HERE] ``` Please: 1. Explain what this error means in simple terms 2. Identify the exact line causing the issue 3. Explain WHY it's happening 4. Provide the corrected code 5. Show how to prevent this error in the future 6. If relevant, mention common variations of this error
Review this Python code for bugs and issues: ```python [PASTE YOUR CODE HERE] ``` Check for: 1. Logic errors and edge cases 2. Off-by-one errors 3. None/null handling issues 4. Type mismatches 5. Resource leaks (files, connections) 6. Race conditions (if applicable) 7. Security vulnerabilities For each issue found: - Line number - Description of the bug - Why it's a problem - Fixed code snippet - Severity (Critical/High/Medium/Low)
This Python code is running slowly: ```python [PASTE YOUR CODE HERE] ``` Analyze and optimize: 1. Identify Performance Bottlenecks: - Time complexity issues (nested loops, etc.) - Memory inefficiencies - Unnecessary operations 2. Suggest Optimizations: - Algorithm improvements - Built-in function replacements - Generator usage opportunities - Caching opportunities 3. Provide Optimized Code: - Show before/after comparison - Explain the improvement - Estimate speedup factor 4. Profiling Tips: - How to measure performance - What to benchmark
Data Analysis Prompts
Pandas, NumPy, and data visualization
I have a dataset with these issues: - Column names: [list column names] - Data types: [describe expected vs actual] - Missing values: [describe patterns] - Duplicates: [yes/no, which columns] Write Python code using Pandas to: 1. Load the data (CSV/Excel/JSON) 2. Standardize column names (lowercase, no spaces) 3. Handle missing values appropriately: - Numeric: fill/interpolate/drop based on context - Categorical: mode or 'Unknown' 4. Remove duplicates based on [key columns] 5. Convert data types correctly 6. Handle outliers in [columns] 7. Create a summary of changes made Include: - Comments explaining each step - Data validation checks - Before/after row counts
Create Python visualization code for this data: Data: [describe your data or paste sample] Chart Type: [bar/line/scatter/heatmap/etc] Purpose: [what story should it tell?] Requirements: 1. Use matplotlib and/or seaborn 2. Publication-quality styling: - Clear labels and title - Appropriate font sizes - Color palette: [specify or 'professional'] - Figure size optimized for [presentation/paper/web] 3. Include: - Legend if multiple series - Data labels if helpful - Gridlines (subtle) - Axis formatting (thousands separator, %, etc.) 4. Save as PNG (300 DPI) and SVG 5. Make it accessible (colorblind-friendly) Add comments explaining customization options.
Perform statistical analysis on this data: Data Description: [describe your dataset] Variables: - Dependent: [variable name and type] - Independent: [variable names and types] Analysis Goals: [what question are you answering?] Write Python code to: 1. Descriptive Statistics: - Mean, median, std, quartiles - Distribution visualization - Identify outliers 2. Appropriate Statistical Test: - Determine correct test based on data - Check assumptions (normality, etc.) - Run the test - Calculate effect size 3. Results Interpretation: - p-value interpretation - Confidence intervals - Practical significance 4. Visualization: - Results chart - Error bars/confidence intervals Use scipy, statsmodels, or pingouin as appropriate.
Automation Script Prompts
Automate repetitive tasks
Create a Python script to process files: Task: [describe what to do with files] Input: [file types, location, naming pattern] Output: [desired result, output location] Requirements: 1. Use pathlib for file operations 2. Handle errors gracefully: - File not found - Permission errors - Invalid file format 3. Progress tracking: - Show files processed - Estimated time remaining 4. Logging: - Log successful operations - Log errors with details - Summary at end 5. Options: - Dry run mode - Recursive directory handling - File filtering by date/size Include: - Command-line arguments (argparse) - Configuration file support (optional) - Example usage in docstring
Create a Python web scraping script: Target: [website URL or description] Data to Extract: [list specific data points] Output Format: [CSV/JSON/database] Requirements: 1. Use requests + BeautifulSoup (or Selenium if JS) 2. Respectful scraping: - Check robots.txt - Rate limiting (1-2 sec delay) - User-agent header 3. Error handling: - Connection timeouts - 404/500 errors - Missing elements 4. Data cleaning: - Strip whitespace - Handle encoding - Validate extracted data 5. Features: - Resume capability - Progress saving - Duplicate detection Include legal/ethical considerations in comments. Note: Ensure you have permission to scrape.
Create a Python script to interact with an API: API: [name or describe the API] Endpoints Needed: [list endpoints] Authentication: [API key/OAuth/Bearer token] Requirements: 1. Use requests library 2. Proper authentication handling: - Secure credential storage - Token refresh if needed 3. Error handling: - Rate limit (429) with backoff - Auth errors (401/403) - Server errors (500) 4. Features: - Pagination handling - Response caching - Request logging 5. Clean code: - Type hints - Docstrings - Environment variables for secrets Create a reusable API client class. Include example usage.
Python Testing Prompts
Write tests for your Python code
Generate unit tests for this Python code: ```python [PASTE YOUR CODE HERE] ``` Requirements: 1. Use pytest framework 2. Test coverage: - Happy path (normal inputs) - Edge cases (empty, None, boundary values) - Error cases (invalid inputs) - Type edge cases 3. Test structure: - Arrange-Act-Assert pattern - Descriptive test names - One assertion per test (usually) 4. Include: - Fixtures for setup/teardown - Parametrized tests where appropriate - Mock external dependencies 5. Documentation: - Docstrings explaining test purpose - Comments for complex assertions Generate a complete test file ready to run.
Create mocks for testing this code: ```python [PASTE CODE THAT USES EXTERNAL SERVICES] ``` External Dependencies: - [List: API calls, database, file system, etc.] Create: 1. Mock objects for each dependency 2. Fixtures to inject mocks 3. Realistic fake data 4. Different response scenarios: - Success responses - Error responses - Timeout scenarios - Edge case data Use: - unittest.mock or pytest-mock - responses library for HTTP mocking - mongomock/fakeredis for databases Include examples of: - Patching at correct location - Asserting mock was called correctly - Side effects for multiple calls
Level Up Your Python Development
Save all 30+ Python prompts. Access from anywhere, organize by project, and customize for your workflow.
Get 10 Free AI Prompt Templates
Join 2,000+ professionals getting weekly prompt tips and templates. No spam, unsubscribe anytime.