Lab 1: Python On-Ramp with Qahwa House¶
In this lab you learn enough Python and pandas to answer a real business question with data.
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 = ... # SAR per latte
margin_pct = ... # percent of the price
print(margin, margin_pct)check("A1 margin", margin == 13)
check("A1 margin percentage", round(margin_pct, 1) == 72.2)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 = ...
average = ...
best_day = ...
print(total, round(average, 1), best_day)check("A2 total", total == 288)
check("A2 average", round(average, 2) == 41.14)
check("A2 best day", best_day == 49)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):
...
print(margin_pct(18, 5), margin_pct(9, 5))check("A3 latte", round(margin_pct(18, 5), 1) == 72.2)
check("A3 croissant", round(margin_pct(9, 5), 1) == 44.4)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():
...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)
...| 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 = ...
iced_uni_units = ...
print(len(iced_uni), iced_uni_units)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())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["cost"] = ...
sales["profit"] = ...
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)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 = ...
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")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 = ...
by_productB7. 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 = ...
daily.head()check("C1 one row per branch and day", len(daily) == 1460)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 = ...
change_pct = ...
print(compare.round(0))
print(change_pct.round(1))check("C2 revenue goes up on promotion days", change_pct["revenue"] > 0)
check("C2 profit goes down on promotion days", change_pct["profit"] < 0)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.
by_cat = ...
by_catcheck("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])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.
Write your recommendation here (double-click to edit).
★ 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# E2# E3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.