Prompt Engineering: Talking to the Junior Dev ๐ค๐ฃ๏ธ โ
Imagine you have a very fast, very eager, but slightly literal-minded Junior Developer sitting next to you.
- If you say "Fix this code," they might delete everything.
- If you say "Make it better," they might add emojis everywhere.
- If you give clear, specific instructions, they will do exactly what you want in seconds.
Prompt Engineering is just the skill of giving good instructions to this Junior Dev.
The 3 Golden Rules ๐ โ
1. Be Specific (Context is King) ๐ โ
The AI doesn't know your project structure, your variable names, or your life story unless you tell it.
| Bad Prompt โ | Good Prompt โ |
|---|---|
| "Write a function to read a file." | "Write a Python function using pathlib that reads a JSON file and returns a dictionary. Handle the FileNotFoundError." |
2. Give Examples (Few-Shot Learning) ๐ฏ โ
Show, don't just tell. If you want a specific output format, give an example.
Prompt:
"Convert these names to email addresses. Example: 'John Doe' -> 'john.doe@company.com' Input: 'Alice Smith'"
3. Iterate (The Conversation) ๐ โ
You rarely get the perfect code on the first try. Treat it like a chat.
- Ask: "Write a script to scrape a website."
- Refine: "Okay, but use
BeautifulSoupinstead ofSelenium." - Fix: "It's crashing on line 10. Here is the error..."
Advanced Techniques for Beginners ๐ โ
The "Persona" Pattern ๐ญ โ
Tell the AI who it should be. This sets the tone and quality of the response.
Prompt:
"Act as a Senior Python Backend Engineer. Explain Python Decorators to me like I am a 10-year-old."
Chain of Thought (Think Step-by-Step) ๐ง โ
If you ask a complex logic question, the AI might guess. Force it to show its work.
Prompt:
"I have a list of numbers:
[10, 2, 5, -1, 0]. I want to find the second largest number. Think step-by-step and explain your logic before writing the code."
Use Delimiters ๐ง โ
Use triple backticks (```) to separate your instructions from your code. This helps the AI understand what is what.
Prompt:
Refactor the code below to use List Comprehensions.
pythonnumbers = [1, 2, 3] squares = [] for n in numbers: squares.append(n * n)
The "ELI5" Pattern (The Teacher) ๐ถ โ
If a concept is confusing, ask the AI to simplify it.
Prompt:
"Explain Python
recursionto me like I am 5 years old. Use an analogy involving Russian Nesting Dolls (Matryoshka)."
The "Style Check" Pattern (The Linter) ๐งน โ
You can use AI to check your code against style guides without installing tools.
Prompt:
"Review this code for PEP-8 compliance. Point out any bad variable names or formatting issues."
The "Data Formatter" Pattern (The Intern) ๐ โ
You have messy text and want clean data structures.
Prompt:
"I have this raw string of names and ages: 'John:25, Alice:30, Bob:22'. Convert this into a Python list of dictionaries like
[{'name': 'John', 'age': 25}, ...]."
The "Regex Wizard" Pattern ๐งโโ๏ธ โ
Regular Expressions are hard. Let AI write them.
Prompt:
"Write a Python function using
remodule to extract all phone numbers from a text. Format matches: (123) 456-7890."
The "Syntax Fixer" Pattern (The Typos) ๐ ๏ธ โ
Python hates messy indentation. AI can spot it instantly.
Prompt:
"I am getting an
IndentationError. Fix this code for me.pythondef hello(): print("Hi") ```"
The "Logic Translator" Pattern (English to Code) ๐ฃ๏ธ โ
Struggling to write the if statements? Describe it in plain English.
Prompt:
"Write a Python function
check_access(age, has_ticket)based on this logic: If they are under 18, reject them. If they are 18 or older but don't have a ticket, reject them. Only let them in if they are 18+ and have a ticket."
Result:
def check_access(age, has_ticket):
if age >= 18 and has_ticket:
return True
return FalseThe "Skeleton Builder" Pattern (Scaffolding) ๐๏ธ โ
Don't know where to start? Ask for the structure, not the full code.
Prompt:
"Write the skeleton for a Python script that reads a CSV file and calculates the average. Define the functions I need (like
read_file,calculate_avg) but usepassfor the body."
Result:
def read_file(filepath):
# TODO: Open file and return data
pass
def calculate_avg(data):
# TODO: Calculate average
pass
def main():
data = read_file("data.csv")
print(calculate_avg(data))The Anatomy of a Perfect Prompt ๐งฌ โ
A perfect prompt has 4 parts:
- Role: Who is the AI? ("Act as a Senior Python Engineer...")
- Task: What should it do? ("Write a unit test...")
- Context: What constraints? ("Using
pytest, focusing on edge cases...") - Output: How should it look? ("Output only the code block, no explanation.")
Task: The "Bad" Prompt
Try asking ChatGPT: "Write code." See what happens. It will likely ask "What kind of code?" or write a generic "Hello World".
Example: The "Iterative" Game ๐ฎ โ
Let's say you want to build a Number Guessing Game.
Round 1 (The Draft):
"Write a Python number guessing game." Result: It writes a simple script. But it might just pick a random number and ask once.
Round 2 (The Refinement):
"Make it so the user has 5 attempts. Tell them if they are 'Higher' or 'Lower'." Result: Now it has a loop and logic.
Round 3 (The Polish):
"Add error handling. If the user types 'banana', don't crash. Just say 'Please enter a number'." Result: A robust, beginner-friendly game.
The Final Code:
import random
def play_game():
secret_number = random.randint(1, 100)
attempts = 5
print(f"I am thinking of a number between 1 and 100. You have {attempts} attempts.")
for i in range(attempts):
user_input = input("Guess: ")
if not user_input.isdigit():
print("Please enter a valid number.")
continue
guess = int(user_input)
if guess == secret_number:
print("You won! ๐")
return
elif guess < secret_number:
print("Higher! โฌ๏ธ")
else:
print("Lower! โฌ๏ธ")
print(f"Game over! The number was {secret_number}.")
play_game()Lesson: Don't expect perfection in one prompt. Build it layer by layer.
Cheat Sheet: Prompting Patterns ๐ โ
| Pattern | Goal | Example Prompt |
|---|---|---|
| Persona | Better quality explanations. | "Act as a Senior Python Teacher..." |
| ELI5 | Understanding complex topics. | "Explain Recursion like I'm 5..." |
| Skeleton | Getting started. | "Write the skeleton structure for this script..." |
| Logic Translator | Writing complex if statements. | "Write code based on this English logic..." |
| Style Check | Fixing messy code. | "Review this for PEP-8 and variable names..." |
| Data Formatter | Cleaning up text. | "Convert this raw text into a list of dicts..." |
The "Temperature" Setting ๐ก๏ธ โ
Most AI tools have a "Temperature" setting (0.0 to 1.0).
- Low (0.0 - 0.2): "The Robot". Logical, deterministic, good for code.
- High (0.7 - 1.0): "The Artist". Creative, random, good for brainstorming ideas.
Tip: When asking for Code, use Low temperature (or tell the AI "Be precise and deterministic"). When asking for App Ideas, use High temperature.
Common Traps โ ๏ธ โ
- Hallucinations: The AI might invent libraries that don't exist. Always verify imports!
- Security: Never paste API keys, passwords, or sensitive company data into a public LLM.
- Over-reliance: Don't copy-paste code you don't understand. If you can't explain it, don't ship it.
Related Topics ๐ โ
- Python Basics: Understand the code the AI is generating.
- Agile Mindset: Learn why iterating on prompts is like the Agile loop.