Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 1 Solutions: Python On-Ramp with Qahwa House

Open In Colab

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.

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).

13 72.22222222222221
✅ 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.

288 41.1 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.

72.22222222222221 44.44444444444444
✅ 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%.

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.

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.

(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
Loading...
ColumnMeaning
date, weekdaythe day
branch, citywhere
product, categorywhat was sold (Drink or Food)
list_pricenormal price, SAR per unit
promo1 on promotion days, 0 otherwise
price_paidSAR per unit actually paid (25% lower on promotion days)
unit_costSAR per unit to make
unitsunits 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?

365 14134
✅ 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 paid

  • cost = units × unit cost

  • profit = revenue − cost

Loading...
✅ 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.

Loading...
✅ 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?

Loading...

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.

<Figure size 800x400 with 1 Axes>

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.

Loading...
✅ 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.

       revenue  profit
promo                 
0       4891.0  3178.0
1       5461.0  3007.0
revenue    11.7
profit     -5.4
dtype: float64
✅ 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.

Loading...
✅ 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:

  1. what the data shows, with one or two numbers;

  2. what you recommend;

  3. 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?

Loading...

In every branch, average daily profit is lower on promotion days, so the conclusion does not depend on the branch.

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.

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: float64

Even 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:

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: float64

Profit 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.