Exercise: Coffee Orders by Hand

Read a week of Bean Street Coffee's orders with the csv module and answer the owner's questions in plain Python, total sales by store, the best-selling drink and the average order, with four functions that pytest checks.

Apprentice · Python · Updated

By

Rosa, who owns Bean Street Coffee, wants four answers about last week before Monday's meeting: how many orders there were, how much each of the three stores sold, which drink sold the most cups, and what an average order is worth. The week is a CSV file of 600 orders. You'll answer her questions in plain Python, with the csv module, lists, dictionaries and loops, by writing four functions, and tests call each function to check its answer. A notebook comes with the exercise for looking at the orders while you work.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-data-coffee-orders-by-hand, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:

cd ~/python-course
git clone https://github.com/ask-codey/exercise-data-coffee-orders-by-hand.git

Git makes a folder, exercise-data-coffee-orders-by-hand, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):

python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt

On a Mac (zsh):

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

The prompt starts with (.venv) once the virtual environment is on. The exercise's README says what each command does, and what to do if PowerShell won't run the second one. Then make the data, once:

python seed.py
Wrote orders.csv: 600 orders.

The folder holds:

  • seed.py: makes orders.csv, the week's 600 orders from Monday, November 2 to Sunday, November 8, our own made-up data. Its fixed random seed means everyone gets the same rows. The columns are order_id, date, time, store, drink, size, quantity and unit_price.
  • orders.py: the four functions, for you to finish.
  • explore.ipynb: a notebook for looking at the orders and trying your code. Choose the .venv kernel with Select Kernel (top right) before you run it. The tests don't read it.
  • report.py: answers Rosa's questions with your four functions and prints the answers. Ready to use.
  • tests/: the tests, which call each function and check what comes back, and conftest.py, which gives every test its own fresh copy of the week. You don't need to change them.
  • requirements.txt and pytest.ini: the packages the exercise needs (ipykernel for the notebook, and pytest), at exact versions, and where pytest finds the tests and your code. Your code itself uses only Python's standard library.

What to do

Every function in orders.py is already declared with its name and parameter, and for now it stops with a NotImplementedError that says Not built yet. The docstring under each one says what it should do, with examples:

def best_selling_drink(orders):
    """Return the name of the drink that sold the most cups (the most quantity, not the most orders).

    If two or more drinks sold the same number of cups, return the one whose name comes first
    in alphabetical order. With no orders, return None.

    latte 1 cup, chai 3 cups, latte 1 cup -> "chai" (3 cups beat latte's 2)
    mocha 2 cups, chai 2 cups -> "chai" (a tie, and "chai" comes first)
    """
    raise NotImplementedError("Not built yet.")

In each function, replace the raise NotImplementedError("Not built yet.") line with your own code:

  1. read_orders(path) reads the CSV file at path with csv.DictReader and returns a list of dictionaries, one per order, in the file's order. Each dictionary has the eight columns as its keys. quantity becomes an int and unit_price a float; every other value stays text. The row 1001,2026-11-02,07:05,Downtown,latte,M,2,4.45 becomes {"order_id": "1001", "date": "2026-11-02", "time": "07:05", "store": "Downtown", "drink": "latte", "size": "M", "quantity": 2, "unit_price": 4.45}.
  2. total_by_store(orders) returns a dictionary with each store's name as a key and its total sales as the value. An order's sale is its quantity times its unit price; round each store's total to cents with round(total, 2). Downtown 2 × 4.45 and 1 × 4.75, and Campus 3 × 4.35, give {"Downtown": 13.65, "Campus": 13.05}. With no orders, it returns {}.
  3. best_selling_drink(orders) returns the name of the drink that sold the most cups, counting quantities, not orders. A tie goes to the name that comes first in alphabetical order, and with no orders it returns None.
  4. average_order_value(orders) returns every order's sale added up, divided by the number of orders, rounded to cents. Orders of 2 × 4.45, 1 × 4.75 and 1 × 2.95 make (8.90 + 4.75 + 2.95) / 3, which rounds to 5.53. With no orders, it returns 0.

The last three functions read the list they're given and leave it unchanged; the tests check that too.

Check your work

Run the tests from the exercise folder, with the virtual environment on:

python -m pytest

At first all 16 tests fail. That's expected: each function you finish turns its tests green. A failing test's message says what it called, what it expected and what came back, for example best_selling_drink(orders) for latte 1 cup, chai 3 cups, latte 1 cup should give 'chai', but it gave 'latte'.

To see your functions answer Rosa's questions about the whole week, run python report.py.

Hints

  • Look before you write. The notebook's first cells read the file with csv.DictReader and show the first order, so you can see that every value arrives as text, as CSV Files: Tables in Plain Text shows.
  • Convert as you read. In read_orders, change row["quantity"] and row["unit_price"] with int() and float() before you add the row to your list.
  • One pattern, two questions. A dictionary of running totals with get(key, 0) answers "sales for each store" and "cups for each drink", as Answering a Question by Hand, and Where It Breaks shows. Only the key and the value you add change.
  • Ties in alphabetical order. sorted(cups) gives a dictionary's keys in alphabetical order. Go through them in that order, and replace your best drink only when a drink has more cups, so the first of a tie stays.
  • Check for no orders first. Dividing by len(orders) when it's 0 stops with a ZeroDivisionError, so return 0 before you get there.

When you're done

Every test is green: pytest's last line says 16 passed. And python report.py prints:

1) orders read: 600
2) Downtown sales: 1242.95
3) Campus sales: 1028.65
4) Harbor sales: 925.9
5) best-selling drink: latte
6) average order: 5.33

Now count what it took: about thirty lines of loops for four answers, and every new question Rosa asks will cost another loop. Keep that number in mind for the next chapter.

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-data-coffee-orders-by-hand), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-data-coffee-orders-by-hand.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-data-coffee-orders-by-hand, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

Answering a manager's questions with loops and dictionaries is real data work, and it shows you exactly what every table library does underneath: read the rows, convert the numbers, group, add up and divide.

Key terms

Related