Writing Effective Prompts for Code
The quality of code you get from AI depends heavily on how you ask for it. Vague requests produce vague results. Specific, detailed prompts get you working code on the first try. Let's learn to write prompts that work.
Be Specific About Requirements
Compare these two prompts:
Vague: "Write a function to process data"
Specific: "Write a Python function called filter_adults that takes a list of dictionaries with 'name' and 'age' keys, returns only entries where age is 18 or greater, and sorts results by age ascending."
The specific prompt tells the AI exactly what you need: the language, function name, input format, filtering logic, and output order. The AI doesn't have to guess.
Include Context and Constraints
Tell the AI about your situation:
- Language and version: "Using Python 3.10..."
- Dependencies: "Without using any external libraries..."
- Error handling: "Handle the case where the input is empty..."
- Style preferences: "Use type hints and docstrings..."
Each constraint narrows down the possibilities and gets you closer to usable code.
Provide Examples
Examples eliminate ambiguity. Show the AI what you expect:
Input: [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 17}]
Output: [{'name': 'Alice', 'age': 25}]
When the AI sees concrete examples, it understands your requirements precisely.
Structure Your Prompts
A well-structured prompt might look like this:
Write a Python function called calculate_discount that:
- Takes two parameters: price (float) and discount_percent (int)
- Returns the discounted price as a float rounded to 2 decimal places
- Raises ValueError if discount_percent is negative or greater than 100
- Example: calculate_discount(100.0, 20) returns 80.00
This format — function name, parameters, return value, error handling, and example — gives the AI everything it needs.
Start Simple, Add Detail
If you're unsure what you need, start with a basic prompt and refine. Ask for a simple version first, then add requirements in follow-up messages. This iterative approach often works better than trying to specify everything upfront.