Working with Code
Duration: 45 min
Working with Code
Duration: 45 min
Overview
Use LLMs for code generation, review, debugging, and refactoring.
Code Generation Prompt
Write a Python function that:
- Takes a list of dicts with 'name' and 'score' keys
- Returns top N items sorted by score descending
- Handles: empty list, N > list length, negative scores
- Include type hints and docstring
- Follow PEP 8
Code Review Prompt
Review this code for bugs, performance, and security issues.
For each issue: line number, severity (critical/warning/style), and fix.python
def get_user(id):
query = f"SELECT * FROM users WHERE id = {id}"
result = db.execute(query)
return result
` Expected findings:
- Line 2: CRITICAL - SQL injection (use parameterized query)
- Line 1: WARNING - no type hint, no input validation
- Line 3: STYLE - no error handling for missing user
Debugging Prompt
python
prompt = f'''This code produces an error. Explain the root cause in one sentence, then show the fix.Code:
{code}
Error: {error_message}
Refactoring Prompt
Refactor for readability. Keep the same API. Explain each change.def p(d,t=0.05,min=100):
r=[]
for i in d:
if i['a']>min:
x=i['a']*t
r.append({'n':i['n'],'t':x,'f':i['a']-x})
return sorted(r,key=lambda x:x['t'],reverse=True)
`
Quiz
Q1: What is the key benefit of this technique?
- A) Reduces API cost
- B) Improves output quality and reliability for the specific use case ✓
- C) Makes prompts shorter
- D) Only works with GPT-4
Q2: When should you NOT use this technique?
- A) For production applications
- B) For simple tasks where basic prompting already works well ✓
- C) With Claude
- D) On weekends
Q3: What should you always test?
- A) Only happy paths
- B) Edge cases, failures, and adversarial inputs ✓
- C) Nothing - trust the model
- D) Only the system prompt