Coding · Writing code
The Best Prompt for Writing Python Code
The best prompt for Python gives the model a spec rather than a wish: what to build, the exact inputs and outputs, the Python version and which packages are allowed. This prompt makes the model restate the spec as testable behaviors, resolve or flag ambiguities, and only then write complete code with type hints, input validation and I/O kept apart from logic. You get runnable files, the command to run them, a table of edge cases, and a list of what the model could not verify.
Python Script and Module Prompt
Turns a plain-language spec into a complete, typed Python script or module, with assumptions, run commands and edge cases listed separately.
- Works with
- ChatGPT, Claude, Gemini, Cursor
- Difficulty
- Intermediate
- Complexity
- Multi-part reply
- Variables
- 6
- Version
- 1.0
Customize this prompt
Fill in what you know. Anything left blank stays as a [bracketed placeholder]. Nothing you type leaves your browser.
6 variables · fields marked * matter most
# Role You are a senior Python engineer writing code that a colleague will maintain without you. Correct and readable beats clever. # Spec - What to build: [What to build] - Inputs and outputs: [Inputs and outputs] - Form: [Form] - Python version: [Python version] - Dependencies allowed: [Dependencies allowed] - Known edge cases and failure conditions: [Known edge cases] # Before you write code 1. Restate the spec as three to six testable behaviors ("given X, returns or writes Y"). 2. List anything ambiguous. If an ambiguity would change the public interface or the data produced, stop and ask me. For anything smaller, choose the conservative reading and label it ASSUMPTION. # Code requirements - Follow PEP 8. Add type hints to every public function and a docstring that states arguments, return value and exceptions raised. - Keep logic separate from I/O (files, network, command-line arguments, printing) so the logic can be imported and tested on its own. - For a command-line script: argparse, a main() that returns an exit code, and an if __name__ == "__main__" guard. Errors go to stderr with a non-zero exit code. - Validate input where it enters the program. Raise specific exceptions with messages that name the offending value. No bare except, no silently swallowed errors. - Use only syntax and standard-library features that exist in the stated Python version, and import nothing outside the allowed dependencies. If you are not sure a function or parameter exists, say so instead of guessing. - Write every function in full: no placeholder bodies, no TODO comments, no "rest of the implementation here". - Build what the spec asks for and nothing more. Suggest extras in a closing note, not in the code. # Output format 1. Assumptions - a short list, or "None". 2. Code - one fenced code block per file, with the filename on the line above it. 3. How to run - the exact command, plus one sample invocation and the shape of its output. 4. Edge cases - a table with columns: case, how the code handles it. 5. Not verified - anything you could not confirm without executing the code.
Use it when you are
- Writing a one-off data cleanup or file-processing script you still want to be able to read next month
- Drafting a small importable module with a clear public interface before wiring it into a larger project
- Converting a manual spreadsheet or shell routine into a command-line tool with proper arguments and exit codes
- Getting a first implementation from a ticket or written spec that a reviewer can check against stated behaviors
Why this prompt works
The spec is restated before any code exists
Most disappointing generated code solves a slightly different problem than the one you had. Requiring the model to rewrite your request as "given X, returns Y" behaviors exposes that drift in the first few lines of the reply, where it costs one sentence to correct. Those same behaviors later double as a checklist for reviewing the code and as the seed for unit tests.
Version and dependencies are inputs, not afterthoughts
Python written for one interpreter version can fail on an older one, and a script that quietly imports a third-party package fails on a machine that does not have it. Stating both up front, and telling the model to admit uncertainty about an API instead of guessing, targets the most common reason generated Python does not run the first time.
Logic and I/O are forced apart
A script that reads files, transforms data and prints results inside one function can only be tested by running the whole thing. Asking for the transformation to live in importable functions, with argument parsing and file access at the edges, gives you code you can exercise from a test or a REPL and reuse when the script grows into a module.
Ambiguity has two exits
The prompt separates questions that change the interface or the data from questions that do not. The first kind stops the work; the second becomes a labeled assumption. That avoids both failure modes of a single rule: a model that interrogates you about trivia, and a model that silently guesses about something you will only notice in production.
The reply ends with what was not checked
A chat model that has no execution tool is predicting what the code will do, not observing it. The "Not verified" section makes that explicit and tells you where to look first when you run the script yourself, which is more useful than an unqualified claim that the code works.
How to use it
- Write the task as behavior ("merge these files and drop duplicates"), then put every concrete detail you know about formats, column names and return types under inputs and outputs.
- Set the Python version to the interpreter that will actually run the code, not the newest one. Check with python --version on the target machine.
- Be strict about dependencies. If the script has to run somewhere you cannot install packages, write "Standard library only".
- Read the restated behaviors and the assumptions before the code. If either is wrong, correct it in one reply and ask for the affected functions only.
- Run the code against a small real sample, including one deliberately bad input, and paste any traceback back into the same conversation.
- Use the edge-case table as a starting list for tests, then run a linter and type checker before committing the file.
AI model compatibility
| Model | Status | Notes |
|---|---|---|
| ChatGPT | Expected to work | If a long file is cut off, ask for the remainder of that file from the last complete function instead of regenerating the whole answer. |
| Claude | Expected to work | Anthropic's guidance recommends XML-style tags to separate instructions from supplied material. If you paste sample input data or an existing file, wrap it in tags such as <sample_input> under the Spec section. |
| Gemini | Expected to work | No model-specific adjustment needed. Paste the prompt as written. |
| Cursor | Expected to work | Inside a repository, name the files and conventions the new code must fit (package layout, existing helpers, linter settings) in the task field so the result matches the project rather than a blank slate. |
“Expected to work” means the prompt uses plain, model-independent structure and has been reviewed for that — not that it has been run on that model. A model is marked Tested only when a test record is published below.
Worked example
Scenario: An operations analyst wants to replace a weekly copy-and-paste routine that combines order exports from several stores.
# Role You are a senior Python engineer writing code that a colleague will maintain without you. Correct and readable beats clever. # Spec - What to build: Merge every CSV file in a folder into a single CSV, removing rows that repeat an order_id that has already been seen - Inputs and outputs: Input: a folder path; each CSV has the columns order_id, order_date (YYYY-MM-DD), store, total. Output: one CSV at a path given by an --output argument, sorted by order_date, and a summary line on stdout with rows read, rows written and duplicates dropped - Form: Command-line script - Python version: 3.10 - Dependencies allowed: Standard library only - Known edge cases and failure conditions: Some exports start with a UTF-8 BOM, a file may have the columns in a different order, and the folder may contain no CSV files at all # Before you write code 1. Restate the spec as three to six testable behaviors ("given X, returns or writes Y"). 2. List anything ambiguous. If an ambiguity would change the public interface or the data produced, stop and ask me. For anything smaller, choose the conservative reading and label it ASSUMPTION. # Code requirements - Follow PEP 8. Add type hints to every public function and a docstring that states arguments, return value and exceptions raised. - Keep logic separate from I/O (files, network, command-line arguments, printing) so the logic can be imported and tested on its own. - For a command-line script: argparse, a main() that returns an exit code, and an if __name__ == "__main__" guard. Errors go to stderr with a non-zero exit code. - Validate input where it enters the program. Raise specific exceptions with messages that name the offending value. No bare except, no silently swallowed errors. - Use only syntax and standard-library features that exist in the stated Python version, and import nothing outside the allowed dependencies. If you are not sure a function or parameter exists, say so instead of guessing. - Write every function in full: no placeholder bodies, no TODO comments, no "rest of the implementation here". - Build what the spec asks for and nothing more. Suggest extras in a closing note, not in the code. # Output format 1. Assumptions - a short list, or "None". 2. Code - one fenced code block per file, with the filename on the line above it. 3. How to run - the exact command, plus one sample invocation and the shape of its output. 4. Edge cases - a table with columns: case, how the code handles it. 5. Not verified - anything you could not confirm without executing the code.
What a good response should contain
- A short list of behaviors, such as which copy of a duplicated order_id is kept, stated before the code
- An assumption or a question about files whose headers do not match the expected columns
- One file using csv and argparse from the standard library, with merging logic in a function that takes rows and a separate main() handling paths and exit codes
- A run command with the folder and --output arguments and a description of the summary line
- An edge-case table covering the BOM, reordered columns and the empty folder, and a note that the script has not been executed
This is an illustrative scenario showing how to fill in the prompt and what to look for. It is not a recorded model output. Recorded outputs will be published here once this prompt has a test record.
Testing and editorial review
Status: Untested. Reviewed for structure and clarity by the editorial team. No recorded model test yet.
No test record has been published for this prompt yet. When it is tested, this section will show the model and version, the date, the inputs, the actual output and notes against our seven-point rubric. We do not publish numerical scores.
| Author | TheBestPromptFor Editorial Team — The editorial team writes, reviews and maintains the prompts and guides on TheBestPromptFor. Prompts are drafted with AI assistance and reviewed against published editorial standards. |
|---|---|
| Published | November 15, 2026 |
| Last reviewed | November 15, 2026 |
| Last tested | Not yet tested |
| Version history |
|
Limitations and things to check
- Unless the tool you use can execute code, the model has not run the script. Treat it as unreviewed code until you have run it on real data.
- Library functions and parameters can be misremembered, especially for less common packages. Check unfamiliar calls against the package documentation.
- The prompt produces a first implementation, not a test suite. Pair it with the unit test prompt before relying on the code.
- Security-sensitive work such as handling credentials, parsing untrusted input or running shell commands needs review by someone qualified, whatever the output looks like.
- Performance is not addressed unless you state data sizes or time limits in the spec.
Alternative prompts
Coding
Unit Test Writing Prompt
Produces a case inventory first, then readable tests that check behavior at the boundaries, with suspected bugs flagged instead of encoded as passing.
- ChatGPT
- Claude
- Gemini
- Cursor
Coding
Bug Diagnosis Prompt
Give the model the error, the code and what you expected. It ranks likely causes by evidence, tells you how to confirm each, and proposes a minimal fix.
- ChatGPT
- Claude
- Gemini
- Cursor
Coding
Behavior-Preserving Refactoring Prompt
Restructures code in small, named steps while holding its observable behavior fixed, and reports anything it could not prove equivalent.
- ChatGPT
- Claude
- Gemini
- Cursor
Web Development
Technical Specification Prompt
Interviews you briefly, then drafts a reviewable spec: goals and non-goals, design, alternatives, rollout, risks and open questions.
- ChatGPT
- Claude
- Gemini
Related resources
Guide
How to Write a Good AI Prompt
The five parts of a complete prompt (goal, context, task, constraints, output format), with a worked rewrite and a pre-send checklist.
Technical guide
How to Test AI Prompts
A seven-criterion rubric and a nine-field test record for evaluating prompts, plus why this site describes results in words and publishes no scores.
Frequently asked questions
How detailed does the spec need to be?
Detailed enough that two developers would build the same interface from it. Name the input format, the output format and what should happen on bad input. You do not need to describe the algorithm. Anything you leave out will come back either as a question or as a labeled assumption, which is a reasonable way to discover what you forgot.
Can I use this for a larger program with several modules?
It is designed for a script, a single module or a small package of two or three files. For anything larger, use it one module at a time and state the interfaces of the neighboring modules in the task field. A written technical spec first will give better results than one very long code request.
Why does the prompt forbid extra features?
Unrequested additions such as logging frameworks, configuration files and retry logic make generated code longer, harder to review and more likely to contain an error. The prompt asks the model to propose extras in a closing note instead, so you can choose what is worth adding rather than deleting what you did not want.
Sources and references
- PEP 8 – Style Guide for Python Code — Python Software Foundation
- Prompt engineering overview — Anthropic
- Prompt engineering guide — OpenAI
Was this prompt useful?
No account needed. Do not include personal information.