Python + AI/ML · Tutorial 11 of 12
Prompt Engineering Basics: getting useful answers from AI
By the FUTEAC Team · 24 November 2026 · 14 min read · Beginner
In short
A good answer starts with a good prompt. A prompt is a briefing, not a search query: who the AI is helping, what to do, what it knows, the shape of the answer, and the limits to respect. This tutorial runs one job through a vague prompt and a specific one, then shows iteration and calling an AI from Python.
- A prompt is a briefing, not a search query. A search box guesses what you mean. An AI answers what you wrote, including the gaps.
- Five parts make a prompt work: role, task, context, format, constraints. Miss one and the answer guesses at it.
- Vague prompts get generic answers that guess at your data. Our vague prompt invented columns we never had and filled missing prices with zero.
- Iterate inside one conversation. A follow-up in the same chat builds on the last answer. A fresh call has no memory, so paste the code back in.
- AI answers vary, and they can be wrong with confidence. Run the code, check the numbers, and never trust an answer you have not tested.
- Never paste secrets into a prompt. No API keys, no passwords, no private customer data. That rule comes from the data ethics side of this roadmap, and it has no exceptions.
- This tutorial feeds the AI & Machine Learning: First Steps course (/course/ai-ml-first-steps) and the Prompt Engineering (/skill/prompt-engineering) skill.
Before you start
What a prompt actually is
A prompt is the text you send to an AI, and the answer is shaped by it far more than beginners expect. Type a question into a search engine and it guesses your intent from a few words. Send a short prompt to an AI and it does the same thing, except it cannot ask you what you meant. It fills the gaps with its best guess, and its guesses look confident.
Think of briefing a new colleague on their first day. "Clean the data" means nothing to them. They do not know which file, which columns, what counts as clean, or what to do with the blanks. A good briefing answers those questions before they start. A prompt is the same briefing, written down: who they are helping, what to do, what they know, what shape the result should take, and what limits to respect. The colleague analogy holds for one more reason: a good briefing takes a minute to write and saves an hour of rework, and a vague one does the opposite.
This matters for a Python learner in a specific way. You will use AI tools to explain errors, draft functions and check your understanding, and the quality of those answers decides how fast you learn. A vague prompt gets you an answer that looks right and teaches you nothing, or worse, teaches you a wrong habit. A specific prompt gets you an answer you can run, check and learn from. The rest of this tutorial is one job done both ways, with the real replies.
The five parts of a good prompt
A prompt that works has five parts, and each one stops a different kind of guessing.
- Role. Who the AI is for this answer. "You are a Python tutor for a beginner who knows pandas basics." The role sets the level: no jargon without an explanation, no advanced shortcuts.
- Task. The one job, stated as a verb. "Write a function called clean_prices." One job per prompt. Two jobs get you half of each.
- Context. What the AI needs to know to do the job. "The DataFrame has a column named price with strings like $1,200 and 850. Some values are missing." Without this, the answer invents its own context, and you saw what that looks like in the next section.
- Format. The shape of the answer. "Show only the code, then explain each step in one short sentence each." Format is how you get an answer you can use instead of an essay about the answer.
- Constraints. The limits. "Leave missing values empty instead of filling them. Keep the whole answer under 180 words." Constraints are where your judgement lives: the things you know from item 27 that the model does not.
You do not need all five in every prompt. A quick question needs two. But when an answer comes back wrong, the fix is almost always a missing part, not a cleverer model. Ask which part you left out, add it, and run the prompt again. That loop is the whole skill, and the next two sections run it for real.
Worked example: one job, two prompts, two very different answers
The job is the same in both runs: write Python code that cleans a price column. First the vague prompt, exactly as sent:
Write Python code to clean data.What came back: a long "data-cleaning toolbox", eleven numbered sections, written for a dataset the model invented. It guessed at columns we never had, gender and signup_date, and told us to replace "your_dataset.csv" with our file. It is not a bad toolbox. It is an answer to a question we never asked, and it ends with the reader doing the work of fitting a generic template to their real data. That is the tax a vague prompt charges: the answer is long, the useful part is buried, and the specifics are yours to supply afterwards.
The specific prompt, exactly as sent:
You are a Python tutor for a beginner who knows pandas basics. Write a
Python function called clean_prices that takes a pandas DataFrame with a
column named price containing strings like $1,200 and 850, and returns
the DataFrame with price as numbers. Leave missing values empty instead
of filling them. Show only the code, then explain each step in one short
sentence each. Keep the whole answer under 180 words.What came back, in full:
import pandas as pd
import re
def clean_prices(df: pd.DataFrame) -> pd.DataFrame:
def _to_num(x):
if pd.isna(x):
return x
# Remove any $ and commas, then convert to float
return float(re.sub(r"[,$]", "", str(x)))
df = df.copy()
df['price'] = df['price'].apply(_to_num)
return df- Import
pandasand the regex module. - Define
clean_priceswith a typedDataFrameargument. - Inside, create
_to_num: skip NaN, strip$and commas, coerce to float. - Copy the DataFrame to avoid altering the original.
- Replace the
pricecolumn by applying_to_numrow-wise. - Return the modified copy.
Short, exact, and every line answers the prompt. The constraint did real work: missing values stay empty, as item 27 teaches. The format did real work: code first, then one sentence per step, no essay. The role did real work: a typed function with a plain explanation, not an advanced one-liner.
Run it, because an answer you have not run is a rumour:
df = pd.DataFrame({"price": ["$1,200", "850", None, "$99.50"]})
out = clean_prices(df)
print(out)
print("original untouched:", df["price"].tolist())Expected behaviour: the code prints the cleaned column, 1200.0, 850.0, NaN, 99.5, and the original still holds ['$1,200', '850', nan, '$99.50']. The function works, and the copy means the original data is untouched, which is the behaviour a beginner should expect and the answer actually delivers.
Iterate: the follow-up that lost the thread, and the one that worked
A first answer is rarely the last word. The job changes: empty strings and the text "not available" should also count as missing. The natural move is a follow-up in the same chat: "Update the clean_prices function from your last answer so it also handles empty strings and the text 'not available' by leaving them empty."
That follow-up failed, and the reason matters. It was sent as a fresh call, with no memory of the earlier answer, so "your last answer" pointed at nothing. What came back was a different function with a new signature, clean_prices(df, cols), three chained replace calls with broken patterns, and pd used without an import. It also did not do the job it was asked for in a usable form. The lesson is not that follow-ups do not work. It is that a follow-up only works where the conversation lives. In a chat tool, the thread remembers. In a fresh API call, there is no thread, so you must paste the context back in yourself.
The same follow-up, with the function pasted into the prompt, worked. The prompt was: "Here is a Python function. Update it so empty strings and the text 'not available' in the price column are also left empty instead of causing an error. Show only the changed function, then one sentence saying what changed. Keep it under 120 words." Then the full function from the previous section.
What came back:
def clean_prices(df: pd.DataFrame) -> pd.DataFrame:
def _to_num(x):
if pd.isna(x) or x == '' or str(x).lower() == 'not available':
return pd.NA
return float(re.sub(r"[,$]", "", str(x)))
df = df.copy()
df['price'] = df['price'].apply(_to_num)
return dfThe update adds checks for empty strings and the text "not available" and returns pd.NA.
Same function, same shape, one change. Run it on the wider data:
df = pd.DataFrame({"price": ["$1,200", "850", None, "", "not available", "$99.50"]})
print(clean_prices(df)["price"].tolist())Expected behaviour: the code prints [1200.0, 850.0, <NA>, <NA>, <NA>, 99.5]. The two new cases land as missing, exactly as asked. Two rules fall out of this. First, iterate inside one chat thread when you are chatting, and paste the working code into a new prompt when you are not. Second, judge an iteration by the diff: if the answer rewrites the whole function instead of changing one thing, it lost the thread, and you should say so and paste the code in again.
From Python: build the prompt in code and call an AI
Chat is for learning. Code is for repeating. The five parts of a prompt are just strings, so they can be built by a function, and the call itself is an ordinary web request, the pattern from item 61. This example uses a free text endpoint that needs no key or signup, so you can run it exactly as written. Paid tools work the same way, with the endpoint swapped and a key sent in a header, which the end of this section covers.
import requests
def build_prompt(role, task, context, format_, constraints):
parts = [
f"You are {role}.",
f"Task: {task}",
f"Context: {context}",
f"Format: {format_}",
f"Constraints: {constraints}",
]
return "\n".join(parts)
def ask_ai(prompt):
url = "https://text.pollinations.ai/" + requests.utils.quote(prompt)
response = requests.get(url, headers={"Accept": "text/plain"}, timeout=90)
response.raise_for_status()
return response.text.strip()
prompt = build_prompt(
role="a Python tutor for a beginner who knows pandas basics",
task="write a function called clean_prices that turns a price column "
"of strings like $1,200 into numbers",
context="the DataFrame has a column named price; some values are missing",
format_="code first, then one short sentence per step",
constraints="leave missing values empty; under 180 words",
)
print(prompt)
print("---")
print(ask_ai(prompt))Expected behaviour: the script prints the built prompt, then the answer below, which is the real reply from the November 2026 run. Your run will differ in wording. The shape, a short function that honours the constraints, is what should match.
import pandas as pd
import numpy as np
def clean_prices(df: pd.DataFrame) -> pd.DataFrame:
# Copy to avoid modifying original DataFrame
out = df.copy()
# Keep existing NaNs and strip dollar sign and commas from strings
out['price'] = out['price'].apply(
lambda x: np.nan if pd.isna(x) else float(x.replace('$', '').replace(',', ''))
)
return out- Import the libraries you'll need.
- Define the function, accepting a DataFrame.
- Make a copy so the input stays unchanged.
- Use
applyto process each entry: leave NaNs untouched, otherwise strip$and,. - Convert the cleaned string to a float.
- Return the modified copy.
Two things to check before you reuse it. First, run it on string data and it works: ["$1,200", "850", None, "$99.50"] comes back as [1200.0, 850.0, nan, 99.5]. Second, it assumes every value is a string. Put a plain number in the column and it fails with AttributeError: 'int' object has no attribute 'replace', because a number has no replace method. The chat answer from the previous section used str(x) inside its conversion, which handles mixed types. That is the difference between an answer that works on the example and one that works on real data, and it is why you run AI code on your own data before you trust it.
With a paid provider, the shape is the same and two things change: the URL becomes the provider's endpoint, and the key travels in an Authorization header, read from an environment variable, never written in the code. Keys live in the provider's dashboard, and the free tiers of the main chat tools cover learning use. Never paste a key into a prompt, a chat message, or a shared file. That rule has no exceptions, and it is the same rule the data ethics skill teaches for customer data.
Do models check your facts?
Not reliably, so do not lean on it. We tested one loaded question: "Why does pandas read_csv sort my rows alphabetically when I load a CSV file?" The premise is false, and this time the model pushed back. Its first line was that read_csv itself never re-orders rows, and it listed the real causes, a sort call later in the script, an index column, or a file that was already sorted. That is the good case.
The good case is not a promise. The same model, asked a different loaded question on a different day, may explain the false premise instead of correcting it. The habit to build is simple: when an answer explains why something happens, check the claim before you believe the explanation. For pandas, that means running three lines on your own file and looking at the order. For anything else, it means testing the claim the same way you test code. An AI is a fast first draft, not a source of truth, and the checking is your job.
The wrong turn: the vague answer's price code, run for real
The vague prompt's toolbox ended its price handling with two lines that look sensible:
if 'price' in df.columns:
df['price'] = pd.to_numeric(df['price'], errors='coerce')
df['price'].fillna(0, inplace=True) # or any other strategyRun those two lines on our price data, ["$1,200", "850", None, "$99.50"], and see what actually happens:
df = pd.DataFrame({"price": ["$1,200", "850", None, "$99.50"]})
df['price'] = pd.to_numeric(df['price'], errors='coerce')
print("after to_numeric:", df['price'].tolist())
df['price'].fillna(0, inplace=True)
print("after fillna(0):", df['price'].tolist())Expected behaviour: the code prints after to_numeric: [nan, 850.0, nan, nan] and after fillna(0): [nan, 850.0, nan, nan], plus a ChainedAssignmentError warning from pandas. Two things went wrong, and both are worth naming. First, to_numeric cannot read "$1,200" or "$99.50", so both real prices became missing. The dollar sign and comma have to be stripped first, which is exactly what the specific prompt's answer did. Second, the fill did nothing at all. In pandas 3.1.1, fillna(0, inplace=True) on a column selection does not update the data, and pandas warns you about it. The line reads like it fills missing prices with zero, and it silently leaves them missing.
And the intended behaviour is no better. Written the working way, df['price'] = df['price'].fillna(0), the same data comes back as [0.0, 850.0, 0.0, 0.0]. Two real prices, $1,200 and $99.50, have become zero. A missing price is not a free item, and a $1,200 item is not a $0 item. The specific prompt's constraint, "leave missing values empty", exists precisely to stop this. The wrong turn is not that the model wrote bad code. It is that a vague prompt gave it no reason to know what "clean" meant for your data, so it guessed, and its guess quietly destroyed two prices.
Try it yourself
1. Send the vague prompt, "Write Python code to clean data", to your own chat tool, then send the specific prompt from this tutorial. Compare the two answers: which one names your columns, and which one invents its own? 2. Take the specific prompt and remove the constraints line. Run it again. What changes in the answer, and does it still leave missing values empty? 3. Ask for the same clean_prices function, but add a new constraint: "the function must also handle prices in euros, like 850 EUR". Read the answer, run the code, and write down what it got right and what it missed. 4. Run the build_prompt script from the Python section, then change one part, the format, to "explain it like I am ten years old". Compare the two answers and note which part of the prompt moved the answer most. 5. Ask your chat tool a loaded question about a tool you know well, one with a false premise, and see whether it corrects you or explains the false premise. Write down which it did.
Continue in the free course: AI & Machine Learning: First Steps →
Common mistakes
- Writing a prompt like a search query. "Clean the data" gets a generic toolbox that invents columns. Say who it is for, what to do, what the data looks like, the shape of the answer, and the limits.
- Giving two jobs in one prompt. "Write the function and explain pandas" gets half of each. One job per prompt, then a follow-up for the second job.
- Skipping the constraints. Without "leave missing values empty", the model fills them with zero, and a $1,200 price becomes $0. Your judgement belongs in the prompt, not in the hope that the model shares it.
- Following up in a fresh call without pasting the context. "Update your last answer" points at nothing when there is no thread. Paste the code back in, or stay in the same chat.
- Trusting AI code you have not run. The Python section's answer fails on a plain number with
AttributeError: 'int' object has no attribute 'replace'. Run every answer on your own data, including the awkward rows. - Pasting secrets into a prompt. API keys, passwords and private customer data do not belong in a chat window. Keys live in environment variables, and private data stays out of prompts entirely.
- Treating the answer as a source of truth. The model corrected a false premise about
read_csvonce, and it may not do so next time. Check claims the same way you test code: run them.
Frequently asked questions
Which AI chat tool should I use?
Any of the main ones, ChatGPT, Claude or Gemini, works for the chat examples in this tutorial. They differ in wording and small habits, not in the skill being taught. Pick the one you already have, learn the prompting habit there, and the habit travels with you.
Do I need to pay for an API key to follow the Python section?
No. The example uses a free endpoint that needs no key or signup, so the script runs exactly as written. A paid provider follows the same shape with a different URL and a key in a header, and the free tiers cover learning use.
Why did the vague prompt get such a long answer?
Because it had to guess everything: the dataset, the columns, the goal, the format and the length. Long answers are often a sign of a missing part in the prompt, not of a thorough model. Add the missing part and the answer gets shorter and more exact.
Will the same prompt give the same answer twice?
Not necessarily. The vague prompt in this tutorial returned identical text on both runs in November 2026. The specific prompts returned the same shape each time, a short function that honoured the constraints, with wording that varies run to run. Treat every AI answer as a fresh draft, and judge it by whether it meets your constraints, not by whether it matches a previous run.
Can I use AI to write all my code?
You can, and you will learn slowly if you do. The pillar's warning stands: prompting is not a substitute for learning Python. Use the AI to explain, to draft, and to check your work, and run everything it gives you. The understanding comes from reading the answer and testing it, not from pasting it.
Follow the Python + AI/ML Beginner Roadmap
Learn Python from zero and take your first steps into AI and machine learning. Free, step by step, at your pace.
View the Roadmap