Lab 1 Solutions: Python On-Ramp with Qahwa House¶
These are the worked solutions, with outputs. Try the lab yourself first.
The question. Qahwa House, a café chain with four branches, ran a second cup half price promotion on about one day in seven during 2025. Should it run the promotion again, and on which items?
How this lab works
Run the cells from top to bottom with Shift + Enter.
Guided track: replace every
...with your code, then run the check cell under it. A ✅ means your answer is right.Extended track: after Part C, try the ★ challenges at the end.
Submit before the next lab session: File → Download → Download .ipynb, then upload the file to the course page.
You may use an AI assistant for code. If you do, add a short note at the end of the notebook: what you asked, what you kept and what you changed.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)Part A: Python warm-up¶
A1. Numbers and variables¶
A Spanish latte sells for 18 SAR and costs 5 SAR to make. Store these in two variables, then compute the margin (price minus cost) and the margin percentage (margin divided by price, times 100).
price = 18
cost = 5
margin = price - cost # SAR per latte
margin_pct = margin / price * 100 # percent of the price
print(margin, margin_pct)13 72.22222222222221
check("A1 margin", margin == 13)
check("A1 margin percentage", round(margin_pct, 1) == 72.2)✅ A1 margin
✅ A1 margin percentage
A2. Lists¶
The Al-Kharj branch sold these numbers of lattes over one week, Sunday to Saturday. Use the built-in functions sum, len and max to find the total, the daily average and the best day’s sales.
week = [38, 35, 36, 39, 46, 49, 45]
total = sum(week)
average = total / len(week)
best_day = max(week)
print(total, round(average, 1), best_day)288 41.1 49
check("A2 total", total == 288)
check("A2 average", round(average, 2) == 41.14)
check("A2 best day", best_day == 49)✅ A2 total
✅ A2 average
✅ A2 best day
A3. Functions¶
Write a function margin_pct(price, cost) that returns the margin percentage. Functions let you reuse a calculation, and a model is usually a set of functions.
def margin_pct(price, cost):
return (price - cost) / price * 100
print(margin_pct(18, 5), margin_pct(9, 5))72.22222222222221 44.44444444444444
check("A3 latte", round(margin_pct(18, 5), 1) == 72.2)
check("A3 croissant", round(margin_pct(9, 5), 1) == 44.4)✅ A3 latte
✅ A3 croissant
A4. Dictionaries and loops¶
A dictionary maps keys to values. Here each product maps to its (price, cost) pair. Loop over it and print one line per product with its margin percentage, using your function from A3 and an f-string. The first line should read Arabic Coffee: 75.0%.
menu = {
"Arabic Coffee": (8, 2),
"Spanish Latte": (18, 5),
"Croissant": (9, 5),
"Chicken Sandwich": (19, 11.5),
}
for product, (p, c) in menu.items():
print(f"{product}: {margin_pct(p, c):.1f}%")Arabic Coffee: 75.0%
Spanish Latte: 72.2%
Croissant: 44.4%
Chicken Sandwich: 39.5%
Notice the gap between drinks and food. Keep it in mind for Part C.
Part B: pandas basics¶
pandas is the Python library for tables of data. A table is called a DataFrame; each column is a Series.
B1. Load the data¶
The cell below downloads the Qahwa House sales for 2025 from the course website. Run it as it is.
import pandas as pd
DATA_URL = "https://chebil.github.io/BusinessDecision/data/qahwa_sales_2025.csv"
try:
sales = pd.read_csv(DATA_URL)
except Exception: # offline, or working from a copy of the course repository
sales = pd.read_csv("../data/qahwa_sales_2025.csv")B2. First look¶
Use sales.shape to find the number of rows and columns, sales.head() to see the first rows, and sales.info() to see each column’s type. Each row is one product, in one branch, on one day.
print(sales.shape)
sales.info()
sales.head()(11680, 11)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 11680 entries, 0 to 11679
Data columns (total 11 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 date 11680 non-null object
1 weekday 11680 non-null object
2 branch 11680 non-null object
3 city 11680 non-null object
4 product 11680 non-null object
5 category 11680 non-null object
6 list_price 11680 non-null float64
7 promo 11680 non-null int64
8 price_paid 11680 non-null float64
9 unit_cost 11680 non-null float64
10 units 11680 non-null int64
dtypes: float64(3), int64(2), object(6)
memory usage: 1003.9+ KB
| Column | Meaning |
|---|---|
date, weekday | the day |
branch, city | where |
product, category | what was sold (Drink or Food) |
list_price | normal price, SAR per unit |
promo | 1 on promotion days, 0 otherwise |
price_paid | SAR per unit actually paid (25% lower on promotion days) |
unit_cost | SAR per unit to make |
units | units sold that day |
B3. Select and filter¶
sales["units"]selects one column;sales[["branch", "units"]]selects several.sales[sales["city"] == "Jeddah"]keeps the rows that satisfy a condition. Combine conditions with&and put each in parentheses.
Keep only the Iced Latte rows of the University branch, and store them in iced_uni. How many units did that branch sell in the whole year?
iced_uni = sales[(sales["branch"] == "University") & (sales["product"] == "Iced Latte")]
iced_uni_units = iced_uni["units"].sum()
print(len(iced_uni), iced_uni_units)365 14134
check("B3 one row per day", len(iced_uni) == 365)
check("B3 annual units", iced_uni_units == sales.query("branch == 'University' and product == 'Iced Latte'")["units"].sum())✅ B3 one row per day
✅ B3 annual units
B4. New columns¶
Add three columns, each computed from existing ones for every row at once:
revenue= units × price paidcost= units × unit costprofit= revenue − cost
sales["revenue"] = sales["units"] * sales["price_paid"]
sales["cost"] = sales["units"] * sales["unit_cost"]
sales["profit"] = sales["revenue"] - sales["cost"]
sales.head()check("B4 columns exist", {"revenue", "cost", "profit"} <= set(sales.columns))
check("B4 profit is right", abs(sales["profit"].sum() - (sales["units"] * (sales["price_paid"] - sales["unit_cost"])).sum()) < 1e-6)✅ B4 columns exist
✅ B4 profit is right
B5. Group and summarise¶
groupby splits the table into groups, applies a summary to each group and combines the results. For example, sales.groupby("city")["units"].sum() gives the units sold in each city.
Compute total revenue and total profit for each branch in 2025, sorted from the most to the least profitable branch. Store the result in by_branch.
by_branch = (sales.groupby("branch")[["revenue", "profit"]]
.sum()
.sort_values("profit", ascending=False))
by_branchcheck("B5 Olaya is the most profitable", by_branch.index[0] == "Olaya")
check("B5 University is the least profitable", by_branch.index[-1] == "University")✅ B5 Olaya is the most profitable
✅ B5 University is the least profitable
B6. Profit margin by product¶
For each product, compute total revenue and total profit, then add a column margin_pct = profit / revenue × 100. Sort by margin. Which category earns the thinner margins?
by_product = sales.groupby(["category", "product"])[["revenue", "profit"]].sum()
by_product["margin_pct"] = by_product["profit"] / by_product["revenue"] * 100
by_product = by_product.sort_values("margin_pct")
by_product.round(1)B7. A first chart¶
Run this cell. It adds up revenue by month and branch, then draws one line per branch. Look for the summer and the Ramadan effects.
import matplotlib.pyplot as plt
sales["month"] = pd.to_datetime(sales["date"]).dt.month
monthly = sales.pivot_table(index="month", columns="branch", values="revenue", aggfunc="sum")
ax = monthly.plot(figsize=(8, 4), marker="o", title="Monthly revenue by branch, 2025 (SAR)")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue (SAR)")
ax.grid(alpha=0.3)
plt.show()
Part C: The decision¶
Each branch decides on the promotion for a whole day, so the right unit of comparison is a branch-day: all sales of one branch on one date.
C1. One row per branch-day¶
Group by date, branch and promo, and sum revenue and profit. Use as_index=False so the group columns stay as ordinary columns. Store the result in daily. It should have 4 × 365 = 1,460 rows.
daily = sales.groupby(["date", "branch", "promo"], as_index=False)[["revenue", "profit"]].sum()
daily.head()check("C1 one row per branch and day", len(daily) == 1460)✅ C1 one row per branch and day
C2. Promotion days against normal days¶
Compute the average daily revenue and profit for normal days (promo == 0) and promotion days (promo == 1). Then compute the percentage change from normal to promotion days.
compare = daily.groupby("promo")[["revenue", "profit"]].mean()
change_pct = (compare.loc[1] / compare.loc[0] - 1) * 100
print(compare.round(0))
print(change_pct.round(1)) revenue profit
promo
0 4891.0 3178.0
1 5461.0 3007.0
revenue 11.7
profit -5.4
dtype: float64
check("C2 revenue goes up on promotion days", change_pct["revenue"] > 0)
check("C2 profit goes down on promotion days", change_pct["profit"] < 0)✅ C2 revenue goes up on promotion days
✅ C2 profit goes down on promotion days
C3. Drinks and food separately¶
Repeat the comparison by category: group the row-level sales table by date, branch, promo and category, sum, then average by category and promo. Store the average daily profit table in by_cat with categories as rows and promo as columns.
daily_cat = sales.groupby(["date", "branch", "promo", "category"], as_index=False)[["revenue", "profit"]].sum()
by_cat = daily_cat.pivot_table(index="category", columns="promo", values="profit", aggfunc="mean")
by_cat["change_pct"] = (by_cat[1] / by_cat[0] - 1) * 100
by_cat.round(1)check("C3 food profit falls on promotion days", by_cat.loc["Food", 1] < by_cat.loc["Food", 0])
check("C3 drink profit does not fall", by_cat.loc["Drink", 1] >= by_cat.loc["Drink", 0])✅ C3 food profit falls on promotion days
✅ C3 drink profit does not fall
C4. Your recommendation¶
Write three sentences for the regional manager, who does not read code:
what the data shows, with one or two numbers;
what you recommend;
one thing the data cannot tell us, which could change your recommendation.
Recommendation. On promotion days, Qahwa House’s average branch earned 11.7% more revenue (5,461 SAR against 4,891 SAR a day) but 5.4% less profit (3,007 SAR against 3,178 SAR), because the 25% discount wipes out most of the margin on food: food profit halves (−50%) while drink profit rises slightly (+3.8%). I recommend stopping the promotion on food and, if it continues at all, limiting it to drinks, where it roughly pays for itself. The data cannot tell us whether the promotion brings new customers who come back later at full price; a test that tracks repeat visits, for example with a loyalty app, would settle that before a wider launch.
★ Extended challenges¶
E1. Does it depend on the branch? Repeat C2 for each branch separately. Is there a branch where the promotion raises profit?
E2. A drinks-only promotion. Estimate the extra annual profit if every branch ran the promotion on drinks only, on every Thursday. State each assumption you make.
E3. A fair comparison? Promotion days were chosen at random. Check it: compute the share of promotion days for each weekday. Why would the comparison in C2 be misleading if promotions had always been run on Fridays?
# E1: the promotion effect, branch by branch
per_branch = daily.pivot_table(index="branch", columns="promo", values="profit", aggfunc="mean")
per_branch["change_pct"] = (per_branch[1] / per_branch[0] - 1) * 100
per_branch.round(1)In every branch, average daily profit is lower on promotion days, so the conclusion does not depend on the branch.
# E2: drinks only, every Thursday
# Assumptions: the average uplift seen on 2025 promotion days applies to Thursdays,
# food sales are unaffected, and a year has 52 Thursdays per branch.
drink_gain_per_day = by_cat.loc["Drink", 1] - by_cat.loc["Drink", 0]
annual_gain = drink_gain_per_day * 52 * sales["branch"].nunique()
print(f"extra drink profit per branch-day: {drink_gain_per_day:,.0f} SAR")
print(f"estimated extra profit per year: {annual_gain:,.0f} SAR")extra drink profit per branch-day: 101 SAR
estimated extra profit per year: 20,943 SAR
The gain is small (around 100 SAR per branch-day) and rests on strong assumptions: Thursdays are already busy, so the uplift may differ, and the estimate ignores staff and marketing costs. It is a reason to run a careful test, not to roll the promotion out.
# E3: was the promotion spread evenly over the week?
days = daily.copy()
days["weekday"] = pd.to_datetime(days["date"]).dt.day_name()
days.groupby("weekday")["promo"].mean().round(3).sort_values()weekday
Monday 0.106
Saturday 0.115
Wednesday 0.132
Tuesday 0.144
Friday 0.154
Sunday 0.159
Thursday 0.212
Name: promo, dtype: float64Even a random choice is uneven: 21% of Thursdays were promotion days, against 11% of Mondays. Thursday is a busy day, so promotion days get a small unearned boost in C2. A fairer comparison sets promotion days against normal days of the same weekday:
by_weekday = days.pivot_table(index="weekday", columns="promo", values="profit", aggfunc="mean")
((by_weekday[1] / by_weekday[0] - 1) * 100).round(1).rename("profit change on promotion days (%)")weekday
Friday -6.2
Monday -6.7
Saturday -6.9
Sunday -8.9
Thursday -6.6
Tuesday -7.6
Wednesday -1.9
Name: profit change on promotion days (%), dtype: float64Profit falls on promotion days on every weekday, by 2% to 9%, so the recommendation stands; the overall −5.4% even slightly understates the loss. Had every promotion fallen on a Friday, the busiest day, part of the “promotion effect” would really be the Friday effect. Week 4 returns to this trap, called confounding.