Prompt Engineering Basics
In this lesson: Write better AI prompts — role, context, format, examples and step-by-step instructions — with before/after prompts.
What is prompt engineering?
A prompt is the instruction you give to an AI model. Prompt engineering is writing that instruction so the answer is accurate, in the right format and useful the first time. The model only knows what you tell it plus what it learned in training – it cannot read your mind, your syllabus or your company rules.
The 6 parts of a strong prompt
| Part | Question it answers | Example |
|---|---|---|
| Role | Who should the AI act as? | “You are a CBSE Class 10 science teacher.” |
| Task | What exactly to do? | “Make 5 MCQs on refraction.” |
| Context | What background matters? | “Students are weak in ray diagrams; exam is in 2 weeks.” |
| Format | How should the answer look? | “Table: question, 4 options, answer, one-line reason.” |
| Examples | What does good look like? | One sample question in the style you want |
| Limits | What to avoid? | “No questions from lenses. Use NCERT terms only.” |
Bad vs good prompts
| Weak prompt | Strong prompt |
|---|---|
| “Explain loops.” | “Explain Python for and while loops to a Class 11 student who knows variables but not loops. Use one example about printing a multiplication table, show the output, then list 3 common mistakes. Under 250 words.” |
| “Write an email to parents.” | “Write a polite WhatsApp message (max 60 words) from the class teacher of 7-B to parents: PTM on Saturday 10 am–1 pm, report cards will be shared, students must come in uniform. Hindi and English versions.” |
| “Fix my code.” | “This Python function should return the average of a list but crashes on an empty list with ZeroDivisionError. Explain the cause in 2 lines and give a fixed version that returns 0 for an empty list. Code: …” |
Techniques that work
- Few-shot examples: show 1–3 examples of input → output. The model copies the pattern far better than it follows a description.
- Ask for steps: for maths, logic or debugging, ask it to work step by step before giving the final answer, and to show the final answer clearly on its own line.
- Give the source: paste the chapter text, policy or data and say “answer only from this text; if it is not there, say so”.
- Specify the format: table, bullet points, JSON with named keys, word limits.
- Split big tasks: outline first, then each section; or extract data first, then analyse it.
- Iterate: if the answer is off, tell it exactly what to change instead of starting over.
Few-shot example: classify customer messages
Classify each customer message as ORDER, COMPLAINT, ENQUIRY or OTHER. Reply with only the label. Message: "Please send 2 kg kaju katli to Raja Park tomorrow" Label: ORDER Message: "The ghewar I bought yesterday was stale" Label: COMPLAINT Message: "Are you open on Sunday?" Label: ENQUIRY Message: "Do you deliver to Mansarovar and what is the charge?" Label:
Three examples teach the labels, the style (“only the label”) and the boundary between categories. The answer here should be ENQUIRY.
Prompt templates in Python
When you use an AI model inside an app, build prompts with a function so every request has the same structure and you can test it.
def mcq_prompt(topic, grade, count=5, language="English", avoid=None):
lines = [
f"You are an experienced CBSE Class {grade} teacher.",
f"Create {count} multiple-choice questions on: {topic}.",
f"Language: {language}. Use NCERT terminology.",
"Each question: 4 options (a-d), exactly one correct.",
'Return JSON only: [{"q": str, "options": [str, str, str, str], "answer": "a|b|c|d", "why": str}]',
]
if avoid:
lines.append(f"Do not include questions about: {', '.join(avoid)}.")
return "\n".join(lines)
print(mcq_prompt("Refraction of light", 10, count=3, avoid=["lenses", "power of lens"]))Never trust the output blindly: validate it
Models sometimes add extra text, skip a key or give two correct options. If your program uses the answer, check it with code before saving or showing it.
import json
# a reply copied from an AI model – it added a sentence before the JSON
reply = """Sure! Here are your questions:
[{"q": "Light bends when it passes from air to water. This is called?",
"options": ["Reflection", "Refraction", "Dispersion", "Scattering"], "answer": "b",
"why": "Change of speed in a new medium bends light."},
{"q": "The refractive index of water is about?",
"options": ["1.00", "1.33", "1.50", "2.42"], "answer": "e", "why": "n = c / v"}]"""
def extract_questions(text):
start, end = text.find("["), text.rfind("]") + 1 # keep only the JSON part
data = json.loads(text[start:end])
good, problems = [], []
for i, item in enumerate(data, 1):
if set(item) != {"q", "options", "answer", "why"}:
problems.append(f"Q{i}: wrong keys {sorted(item)}")
elif len(item["options"]) != 4:
problems.append(f"Q{i}: needs 4 options")
elif item["answer"] not in "abcd" or len(item["answer"]) != 1:
problems.append(f"Q{i}: invalid answer {item['answer']!r}")
else:
good.append(item)
return good, problems
good, problems = extract_questions(reply)
print("valid questions:", len(good))
print("problems:", problems)The second question has answer “e”, which is impossible – the code catches it so it never reaches students. Ask the model to fix only that question.
Ready-to-use prompts
| For | Prompt |
|---|---|
| Student – revision | “Quiz me on the Python topic dictionaries, one question at a time. Wait for my answer, tell me if it is right and why, then ask the next harder question. Stop after 8 questions and give me a score.” |
| Teacher – lesson plan | “Make a 40-minute lesson plan for Class 8 on fractions: 5-min warm-up, explanation with an Indian market example, group activity, 5 exit-ticket questions. Table format.” |
| Developer – code review | “Review this function for bugs, edge cases and readability. List issues by severity, then give an improved version with comments. Do not change its behaviour for valid input.” |
| Office – summary | “Summarise this meeting transcript in 5 bullet points, then list action items as a table: task, owner, deadline. Mark unclear items with (?).” |
Safety and honesty rules
- Never paste passwords, OTPs, Aadhaar/PAN numbers, medical or students’ personal data into public AI tools.
- Verify facts, numbers, laws and citations from official sources – AI can invent them.
- For school work, follow your teacher’s rules and mention when you used AI.
- “Prompt injection”: text inside a document can try to give the AI new instructions. In apps, keep your instructions separate and never let documents trigger actions like sending emails.
Practice tasks
- Rewrite “make notes on photosynthesis” using all 6 parts of a strong prompt.
- Create a few-shot prompt that converts informal Hinglish messages into formal English.
- Extend
mcq_prompt()with adifficultyparameter and test the printed prompt. - Add a check in
extract_questions()that rejects duplicate options.
Summary
- Strong prompt = role + task + context + format + examples + limits.
- Few-shot examples and source text give the most reliable answers.
- In apps, build prompts with functions and validate every output with code.
- Protect private data and verify facts.
