Boss lesson · Unit 06
An inventory that saves itself
Load, check, update and save stock without losing it
What you practise
- Load JSON, check it, update stock, write it back, and survive a file that is missing or malformed
Try a question from this lesson
Pick one
A shop keeps its stock as JSON text: how many of each item are left. One tea is sold. What does this program show?
import json
text = '{"tea": 4, "milk": 0}'
stock = json.loads(text)
stock["tea"] -= 1
print(stock["tea"] + stock["milk"])Correct answer
3
Why
json.loads turns the text into a real dictionary, and from then on it is ordinary code: take one from "tea", leaving 3, and add the 0 for "milk". The text itself is not changed. Saving the new stock is a separate step.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Four small jobs
A program that remembers things between runs has four jobs: load the data, check it, change it, save it.
Give each job its own function. Each is small enough to test alone, and each has one way to go wrong.
Three dots stand for a body still to be written.
def load(path): ...
def check(stock): ...
def sell(stock, item, n): ...
def save(stock, path): ...
# stock = load("stock.json")
# sell(stock, "tea", 1)
# save(stock, "stock.json")10 more exercises in the app
- 1× fill the blanks
- 2× multiple choice
- 4× type the answer
- 1× order the lines
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.