Final boss: Inventory
The final challenge uses classes, dicts, loops, errors and f-strings together, the way real Python code does.
raise ValueError("not enough stock") deliberately signals an invalid operation. Unlike return, it interrupts the call until an except ValueError catches it. Validate before changing any quantities so a rejected request leaves the inventory intact.
You can also define your own error type by inheriting from Exception: class OutOfStock(Exception): pass. Raise it like any error, raise OutOfStock("rope"), and catch it by name with except OutOfStock as e:, where str(e) is the message.
del self.items[name] removes a dictionary entry entirely; assigning 0 leaves the key present. dict(items) makes an independent dictionary copy, and self.items.values() supplies just the quantities for sum.
See it run
class Item: def __init__(self, name, qty): self.name = name self.qty = qty class Shelf: def __init__(self): self.items = [] def add(self, item): self.items.append(item) shelf = Shelf() shelf.add(Item("nut", 5)) shelf.add(Item("bolt", 2)) bolt = shelf.items[1] bolt.qty = 9 print(shelf.items[1].qty)
One object can hold others. Follow the arrows from the shelf to its items.
Practice final boss: inventory
Exercise 1
Build Inventory with its own initially empty items dict (name to quantity). Assume supplied quantities are positive:
add(name, qty)adds to the quantity (new names start at 0)remove(name, qty)raisesValueErrorif there isn't enough; it removes the name entirely when the quantity hits 0total()returns the sum of all quantitiesreport()returns a list of"name: qty"strings sorted by name
Exercise 2
Build Stockroom with an independent, initially empty items dict. receive(delivery) adds a dict of positive quantities. fulfill(order) accepts a dict of positive quantities: return False and change nothing if any item is unavailable; otherwise subtract all quantities, delete exhausted names, and return True. Empty orders succeed. Leave the supplied delivery and order dictionaries unchanged.
Exercise 3
Build Warehouse(items) copying a dict of positive quantities. transfer_to(other, name, qty) moves positive stock, deleting an exhausted source name, and returns True. Self, nonpositive, missing, or excessive transfers return False and change neither warehouse. report() returns sorted "name: qty" strings as a list.
Exercise 4
Give the shop its own error type.
- Define
class OutOfStock(Exception)(its body can bepass). - Write
take(stock, name): ifstock.get(name, 0)is 0, raiseOutOfStock(name)before changing anything; otherwise subtract 1 fromstock[name]and return the new count. - Call
take(shelf, "rope")insidetry, catchOutOfStock as e, and storemessage = f"Sorry, no {e}".
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.