Part 6 mini-project: Inventory System

This project uses chapters 26 and 27: classes, __init__, instance methods, and inheritance. Item and Inventory manage a bag of loot.

What to build

Two classes in the same module file:

Item — one collectable thing.

  • Item(name, weight, value) — constructor.
  • Fields: name (string), weight (number), value (number).
  • describe() — one-line summary, e.g. "sword (3.5kg, 50g)".

Inventory — a container of items.

  • Inventory() — constructor; starts with an empty list.
  • Field: items (a list of Item instances).
  • add(item) — append an item.
  • remove(name) — remove the first item with that name; returns it, or None if none matches.
  • list() — print each item's describe() on its own line, then a totals footer.
  • total_weight() — sum of weights.
  • total_value() — sum of values.

main.py:

  1. Creates a few items.
  2. Creates an inventory and adds them.
  3. Lists the inventory.
  4. Removes one item by name.
  5. Lists again.
  6. Prints total weight and value as a summary.

A sample run:

Inventory (3 items):
  - sword (3.5kg, 50g)
  - shield (5.0kg, 30g)
  - potion (0.2kg, 5g)
  Totals: 8.70kg, 85g

(removed sword)

Inventory (2 items):
  - shield (5.0kg, 30g)
  - potion (0.2kg, 5g)
  Totals: 5.20kg, 35g

File layout

Two files. As in Part 5, cd into the project folder first:

cd projects/05-inventory/starter
python main.py

Files (in both starter/ and finished/):

  • inventory.py — defines Item and Inventory as Python classes. Both classes live at the top level; no special export step is needed.

  • main.py — imports both classes and runs the scenario:

    from inventory import Item, Inventory

Hints

  • Both classes use __init__ to set their fields on self.
  • Inventory.remove(name) walks self.items with enumerate looking for a matching name, then self.items.pop(i) drops it.
  • Use an f-string for the totals line in Inventory.list: f"Totals: {self.total_weight():.2f}kg, {self.total_value()}g".
  • Item.describe can return the string rather than printing it, so Inventory.list controls how each line is displayed.

What is fair game

Anything from Parts 2-6: variables, control flow, functions, modules, lists, dicts, classes, methods.

Done?

When the scenario runs cleanly from main.py, you're done. Next: Chapter 31 — From Python to other platforms.