Lesson 7: Prompting for Code Generation
Write effective prompts for generating, debugging, and refactoring code across programming languages.
Code Generation Prompts
Getting LLMs to write code effectively requires understanding how to communicate technical requirements clearly. The best code prompts are specific about language, context, and constraints.
The CODE Framework
| Letter | Meaning | What to Include |
|---|---|---|
| C | Context | What is the project? What does the code need to do? |
| O | Output | What language, framework, style? |
| D | Dependencies | What libraries/APIs are available? |
| E | Examples | Show similar code or expected behavior |
Mental model: Think of code prompts like giving specs to a developer — the more specific your requirements, the less revision needed.
Generating New Code
Basic Code Prompt:
Write a Python function that:
- Takes a list of dictionaries with 'name' and 'score' keys
- Returns a new list sorted by score in descending order
- Handles empty lists gracefully
- Includes type hints and docstring
Advanced Code Prompt:
You are a senior Python developer following PEP 8 style guidelines.
Create a function with these specifications:
- Function name: calculate_moving_average
- Input: data (list of floats), window_size (int)
- Output: list of floats (moving averages)
- Edge cases: empty data → empty list, window_size > len(data) → None
- Include: type hints, docstring with examples, error handling
Dependencies: Only use standard library (no numpy/pandas)
Example usage:
>>> calculate_moving_average([1, 2, 3, 4, 5], 3)
[2.0, 3.0, 4.0]
Key elements for code generation:
- Specify the programming language explicitly
- Describe inputs, outputs, and edge cases
- Mention style preferences (PEP 8, etc.)
- Include example usage
- Specify what libraries are available
Debugging Code Prompts
When you have an error:
I'm getting this error in my Python code:
[Error message]
Here's the code:
[Code snippet]
What's causing this error and how do I fix it?
For systematic debugging:
This code should [expected behavior] but instead [actual behavior]:
[Code]
Please:
1. Identify the bug(s)
2. Explain why they occur
3. Provide the corrected code
4. Explain what changed and why
When you don't understand the error:
I don't understand why this code fails:
[Code]
[Error message]
Please:
1. Explain what the error means in plain English
2. Walk through the code execution step-by-step
3. Identify where it goes wrong
4. Provide a fix with explanation
Refactoring Code Prompts
Basic refactoring:
Refactor this code to be:
- More readable
- Following [language] best practices
- Better modularized
Here's the current code:
[Code]
Keep the same functionality but improve the structure.
Performance optimization:
This function works but is too slow for large datasets:
[Code]
Optimize it for:
- Better time complexity
- Memory efficiency
- Maintaining readability
Explain what optimizations you applied.
Code review style:
Review this code as a senior developer would:
[Code]
Provide feedback on:
1. Correctness
2. Performance
3. Readability
4. Security concerns
5. Best practices violations
Then provide an improved version.
Testing Code Prompts
Unit test generation:
Write unit tests for this function:
[Function code]
Requirements:
- Use pytest framework
- Cover normal cases, edge cases, and error cases
- Include descriptive test names
- Aim for 90%+ code coverage
Test case generation:
For this function: [function signature]
Generate test cases that cover:
1. Happy path (expected inputs)
2. Boundary values (min, max, empty)
3. Error conditions (invalid inputs)
4. Edge cases specific to the logic
Present as a table with: Test Name | Input | Expected Output | Description
Code Explanation Prompts
For learning:
Explain this code to a junior developer:
[Code]
Break it down:
1. What does this code do at a high level?
2. Line-by-line explanation
3. Key concepts used
4. Potential improvements
5. Common mistakes to avoid
For documentation:
Generate comprehensive documentation for this code:
[Code]
Include:
1. Overview description
2. Function/class documentation (JSDoc/docstring format)
3. Parameter descriptions
4. Return value documentation
5. Usage examples
6. Known limitations
Language-Specific Considerations
| Language | Key Prompt Details |
|---|---|
| Python | Mention PEP 8, type hints, virtual environments |
| JavaScript/TypeScript | Specify ES6+, async/await, module system |
| React | Hooks vs class components, state management approach |
| SQL | Database type, schema context, query optimization |
| Go | Error handling patterns, goroutines if applicable |
| Rust | Ownership model, unsafe blocks if needed |
Common Mistakes to Avoid
- Mistake: Vague requirements like "make it better" — Fix: Specify exactly what improvements you want.
- Mistake: Not providing context about existing codebase — Fix: Share relevant code structure and conventions.
- Mistake: Forgetting to mention constraints — Fix: Always specify language version, available libraries, etc.
- Mistake: Not testing generated code — Fix: Always run and verify code before using it.
Professional Tips & Tricks
- For complex functions, break into smaller prompts (one per component).
- Always test generated code in a safe environment first.
- Include error handling requirements upfront — don't add it later.
- Use "show your reasoning" for complex algorithms.
Key Takeaways
- Use the CODE framework: Context, Output, Dependencies, Examples.
- Be explicit about language, style, and constraints.
- For debugging, include both the code and the error message.
- For refactoring, specify what aspects to improve.
- Always test generated code before using it in production.
Next up: Prompting for content creation and writing tasks.
# Code Prompt Examples
## Example 1: Function Generation
Prompt: "Write a Python function to validate email addresses using regex"
Generated Code:
import re
from typing import Optional
def validate_email(email: str) -> bool:
"""
Validate an email address using regex.
Args:
email: The email address to validate
Returns:
True if valid, False otherwise
Examples:
>>> validate_email("user@example.com")
True
>>> validate_email("invalid-email")
False
"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
## Example 2: Debugging Prompt
Prompt: "This code crashes with IndexError. Fix it."
Code:
def get_middle(lst):
return lst[len(lst) // 2]
Fix: Add empty list check
def get_middle(lst):
if not lst:
return None
return lst[len(lst) // 2]Lesson Code (Python)
# Code Prompt Examples
## Example 1: Function Generation
Prompt: "Write a Python function to validate email addresses using regex"
Generated Code:
import re
from typing import Optional
def validate_email(email: str) -> bool:
"""
Validate an email address using regex.
Args:
email: The email address to validate
Returns:
True if valid, False otherwise
Examples:
>>> validate_email("user@example.com")
True
>>> validate_email("invalid-email")
False
"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
## Example 2: Debugging Prompt
Prompt: "This code crashes with IndexError. Fix it."
Code:
def get_middle(lst):
return lst[len(lst) // 2]
Fix: Add empty list check
def get_middle(lst):
if not lst:
return None
return lst[len(lst) // 2]Console Output
Code Prompt Examples
## Example 1: Function Generation
Prompt: "Write a Python function to validate email addresses using regex"
Generated Code:
import re
from typing import Optional
def validate_email(email: str) -> bool:
"""
Validate an email address using regex.
Args:
email: The email address to validate
Returns:
True if valid, False otherwise
Examples:
>>> validate_email("user@example.com")
True
>>> validate_email("invalid-email")
False
"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
## Example 2: Debugging Prompt
Prompt: "This code crashes with IndexError. Fix it."
Code:
def get_middle(lst):
return lst[len(lst) // 2]
Fix: Add empty list check
def get_middle(lst):
if not lst:
return None
return lst[len(lst) // 2]Code Visualization Tips
- Create a code prompt checklist with all required elements.
- Draw a flowchart for the debugging prompt process.
- Compare good vs bad code prompts side by side.
Professional Tips & Tricks
- For complex code, break into multiple prompts — one per function.
- Always specify the language version and available libraries.
- Include example inputs and outputs for clarity.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Code Generation Prompt
Test Your Knowledge
Instant feedbackQuick Check: Prompting for Code Generation
Up next · Continue learning
Prompting for Content & Writing
Master prompts for blog posts, marketing copy, technical writing, and creative content.