Skip to content
Exercise · Final project · lesson 8 of 8

Exercise: inventory

Write the class Inventory, a warehouse that counts the units of each item. Keep the quantities in a dict, and create the attribute for it in __init__(self). The methods are these:

  • add(name, qty) puts qty units of the item name into the warehouse;
  • take(name, qty) takes qty units of the item name out of the warehouse;
  • count(name) returns how many units of the item the warehouse holds;
  • names() returns a list of the item names in alphabetical order.

The stub declares the exception OutOfStockError. If the warehouse holds fewer than qty units of the item name, take raises OutOfStockError and leaves the warehouse unchanged.

  • after add("apple", 5) and add("apple", 3): count("apple") → 8
  • when count("pear") is 2: take("pear", 3) raises OutOfStockError, and count("pear") stays 2
  • after add("pear", 2) and add("apple", 5): names() → ['apple', 'pear']

Constraints: qty is a positive integer; count returns 0 for an unknown item, and take raises OutOfStockError for one; an item taken out in full leaves the warehouse, and names no longer returns it.

Do not add extra imports unless the task says so explicitly.

inventory.py — python
python · 20 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way