…
…
Load a small stationery shop's stock from JSON; add, remove and reprice products, apply sales and restocking movements without letting stock go negative, report bad rows, list low-stock products, save the stock and check it with assert tests.
Daisy Stationery is a small shop across from a high school. It sells 25 products: pens, notebooks, paper, office supplies and art supplies. Until now the stock was written in a notebook, and at the end of the month the question "what should I order?" took hours. The shop owner moved all of September's records into the stock.json file and asks you for a small stock program.
Data: stock.json holds two lists. products: each product's code (PN-01), name, category, stock quantity on hand, reorder_level and price. movements: 136 sale (sale) and restock (restock) records for September. Because the records were typed by hand at the register, a few are bad: a code that does not exist, text instead of a number, zero or negative quantity, an unknown type, a sale larger than the quantity on hand. The values are sample data.
What you will have at the end: a movement processor that skips and reports bad rows and never lets stock go below zero; an order list for the end of the month like this:
Output6 products are low on stock
AR-04 Glue stick 3 / 20 order: 37
PN-03 Ballpoint pen black 12 / 40 order: 68
...and a save function that writes the current stock in the same format, reads it back and checks it, and finally assert tests that pin these rules down.
Lessons used: functions and splitting into parts (14–16), tests with assert (19), an aligned report with f-strings (22), enumerate and sorting (24), dictionaries and record structures (26–28), tuples (29), list comprehensions (30), sorting with lambda (31), try, except, raise (32), JSON files (35).
How to work: The steps share one session; the functions you wrote in the earlier step are used in the later ones. Every cell starts with stock, movements = load_stock("stock.json"), so however many times you run a cell, you start with the same clean data. Test your functions not only with this file but also with small trial stocks: working on one example is not enough.
What you'll do
stock.jsonDownload file
Reading file…
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
All of Daisy Stationery's stock information is in stock.json. The file has two lists: products (each product's code, name, category, quantity on hand as stock, reorder_level and price) and movements (the sales and restocking records for September).
From here on we look products up by code, so we turn the product list into a dictionary: the key is the product code, the value is a small dictionary holding the product's details (lesson 28). The file calls the quantity stock; in the dictionary we rename it quantity, because stock["PN-01"]["quantity"] reads better than stock["PN-01"]["stock"].
load_stock(filename) returns the stock dictionary and the list of movements as a tuple (lesson 29). If the file has no movements, it returns an empty list: the dictionary's get method does this (lesson 26). In the later steps we also read the saved file with this function, and that file will have no movements.
Every cell starts with stock, movements = load_stock("stock.json"): however many times you run the cell, you start with the same clean data.
This step's code cell is for members.
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
When a new product arrives at the shop, it is added to the stock; when a code is scanned at the register, the product is found. Both jobs follow rules, and when a rule is broken the program must not carry on silently: it must raise an error (lesson 32):
| Function | Rule | Error message |
|---|---|---|
find_product(stock, code) | The code must be in the dictionary | No such product: <code> |
add_product(...) | The code must not be used already | Code already exists: <code> |
add_product(...) | Quantity cannot be negative; price cannot be zero or negative | Invalid quantity or price: <code> |
The checks are done before any change: if a rule is broken, the error is raised and the dictionary stays untouched. What to do about it (print a message, skip the row) is up to the caller; the try/except blocks below catch the error and print its message.
This step's code cell is for members.Sign up free
A product that is no longer sold is removed from the list; when the supplier raises prices, the prices of a whole category are updated.
remove_product(stock, code) deletes the product from the dictionary and returns the name of the removed product. For a code that does not exist you do not need to write a new check: find_product already raises an error, so you only need to call it. Functions that use each other make the code shorter and keep each rule in one place (lesson 16).
raise_prices(stock, category, percent) increases the price of every product in that category by the percent, rounds the new price to two decimal places (round, lesson 3) and returns how many products were updated. If the category has no products at all (a typo, such as "pen"), it raises ValueError with the message No such category: <category>; quietly returning 0 would hide the mistake.
This step's code cell is for members.Sign up free
Each movement record is a dictionary: {"date": "2026-09-01", "code": "PN-02", "type": "sale", "quantity": 7}. A sale decreases the stock, a restock increases it. But not every row in the file is clean; rows entered by hand at the register can have these problems:
| Problem | Example | What should happen |
|---|---|---|
| No such code | "code": "PN-99" | find_product raises an error |
| Quantity is not a number | "quantity": "ten" | Quantity is not a number: ten |
| Quantity is not positive | "quantity": -5 | Quantity must be positive: -5 |
| Not enough stock | 40 sold when 18 are left | Not enough stock: NB-04 (18 in stock, 40 requested) |
| Unknown type | "type": "return" | Unknown movement type: return |
The most important rule: stock never goes below zero. If a sale is larger than the quantity on hand, an error is raised and nothing changes. The quantity sometimes arrives as a string ("12"); int() turns it into a number. int("ten") gives Python's own English ValueError; catch it and raise it again with your own message (lesson 32).
apply_movement(stock, movement) returns the product's new quantity when it succeeds.
This step's code cell is for members.Sign up free
Now apply all 136 movements for September in order. One bad row must not stop the whole program: skip that row, note its row number and the reason, and move on to the next one. This is exactly the pattern from lesson 32, "the function raises, the caller decides": apply_movement reports the error, and apply_all catches it and writes it to a list.
apply_all(stock, movements) returns two things: the number of movements applied successfully and a list of errors made of (row number, message) tuples. Row numbers start at 1 (enumerate(..., start=1), lesson 24); to turn the error into text, use str(error).
The order of the movements matters: whether a sale has enough stock depends on the movements before it.
This step's code cell is for members.Sign up free
At the end of the month the shop owner asks: "Which products should I order right away?" A product is low when its quantity is equal to or below its reorder level.
low_stock_list(stock) returns the low products as (code, name, quantity, reorder_level) tuples, with the most urgent first. The measure of urgency is the ratio of the quantity to the reorder level: having 3 left of a product with a level of 30 is more urgent than having 3 left of a product with a level of 8. For the sorting you use sorted with key=lambda ... (lesson 31).
The order suggestion is a simple rule: order enough to bring the product up to twice its reorder level (reorder_level * 2 - quantity).
This step's code cell is for members.Sign up free
When the program closes, the current stock must not be lost. save_stock(stock, filename) writes the stock to a new file in the same format as stock.json: shop and the products list, with each product again having the fields code, name, category, stock, reorder_level and price. In other words, you do the reverse of the conversion in step 1: the quantity in the dictionary becomes stock again in the file.
We do not write the movements to this file: they have all been applied to the stock already. If we wrote them, every sale would be subtracted a second time when the file was loaded and processed again.
Read the file you saved back with the same load_stock function and compare it with the dictionary in memory. This "write, read back, compare" check catches a mistake in the saving code (a forgotten field, a wrong name) right away. Do the comparison with assert (lesson 19): if they are not equal, the program stops with your message.
This step's code cell is for members.Sign up free
As a program grows, a small change in one function can break another place. As in lesson 19, pin down the most important rules with assert tests; after a change, running this cell is enough.
The tests do not use the real file but a small, hand-built trial stock: it should be small enough that you can work out the result in your head. In this step, write at least four tests:
1. A sale decreases the stock.
2. A restock increases the stock.
3. A sale larger than the quantity on hand raises ValueError and the stock does not change.
4. low_stock_list finds the low product.
To test that a function raises an error, call it inside a try block; set a flag to False if no error comes and to True if one does, then test the flag with assert (the pattern from the mini bank project).
This step's code cell is for members.Sign up free