Bitpath

Boss lesson · Unit 06

An inventory that saves itself

Load, check, update and save stock without losing it

12 exercisesabout 3 min

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?

Python
import json

text = '{"tea": 4, "milk": 0}'
stock = json.loads(text)
stock["tea"] -= 1
print(stock["tea"] + stock["milk"])

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.

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

One email when Bitpath is ready to try. Nothing else. Privacy