1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

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) raises ValueError if there isn't enough; it removes the name entirely when the quantity hits 0
  • total() returns the sum of all quantities
  • report() 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 be pass).
  • Write take(stock, name): if stock.get(name, 0) is 0, raise OutOfStock(name) before changing anything; otherwise subtract 1 from stock[name] and return the new count.
  • Call take(shelf, "rope") inside try, catch OutOfStock as e, and store message = f"Sorry, no {e}".

The explanation and tasks are public. Running this lesson requires an account with course access.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest