Skip to content
Python project #11Intermediate

Inventory Tracker

Track stock in and out, price changes, reorder alerts, stock value and a movement history for every item.

Estimated time
~3 hours to build
Files
4 files · 317 lines
Technologies
Python 3, dataclasses, Custom exceptions

Introduction

Every shop needs to know what is in stock, what it is worth and what to reorder. This tracker keeps a movement history for each item so every change can be explained.

Problem statement

Add items with SKU, name, opening quantity, unit price and reorder level. Record stock coming in and going out (with optional notes), change prices, and show a full report with stock value, a low-stock list sorted by urgency and the history of any item. Reject duplicate SKUs, unknown SKUs, non-numeric quantities and attempts to remove more stock than exists.

Objectives

  • Model items with a dataclass and computed properties
  • Validate quantities and prices
  • Keep an audit trail of changes
  • Sort and filter for reports

Features

  • Stock in/out with notes
  • Price changes recorded in history
  • Reorder warnings and a low-stock report
  • Inventory value report
  • Movement history per SKU

Concepts demonstrated

  • Audit trails
  • Validation
  • Computed properties
  • Report formatting

System architecture

Item stores quantity, price, reorder level and a list of movement strings; value and low are properties. Inventory.move validates the quantity and stock level before changing anything and appends a history entry. table prints a list of items; run dispatches commands.

Folder structure

TextProject tree
inventory-tracker/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

152 lines
Pythonmain.py
"""Inventory Tracker: stock levels, movements, reorder alerts and stock valuation.
Commands:
add <sku> <name> <qty> <unit-price> <reorder-level> (name may use underscores for spaces)
in <sku> <qty> [note...] receive stock
out <sku> <qty> [note...] sell or use stock
price <sku> <new-price>
report all items with value
low items at or below their reorder level
history <sku>
quit
"""
import sys
from dataclasses import dataclass, field
class InventoryError(Exception):
pass
@dataclass
class Item:
sku: str
name: str
qty: int
price: float
reorder: int
moves: list[str] = field(default_factory=list)
@property
def value(self) -> float:
return self.qty * self.price
@property
def low(self) -> bool:
return self.qty <= self.reorder
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
def whole(text: str, what: str) -> int:
if not text.isdigit() or int(text) == 0 and what == "quantity":
raise InventoryError(f"{what} must be a positive whole number, not '{text}'")
return int(text)
def price(text: str) -> float:
try:
value = float(text)
except ValueError:
raise InventoryError(f"price must be a number, not '{text}'") from None
if value < 0:
raise InventoryError("price can't be negative")
return round(value, 2)
class Inventory:
def __init__(self):
self.items: dict[str, Item] = {}
def get(self, sku: str) -> Item:
try:
return self.items[sku.upper()]
except KeyError:
raise InventoryError(f"unknown SKU {sku}") from None
def add(self, sku: str, name: str, qty: str, unit_price: str, reorder: str) -> Item:
if sku.upper() in self.items:
raise InventoryError(f"SKU {sku.upper()} already exists")
item = Item(sku.upper(), name.replace("_", " "), whole(qty, "opening stock"), price(unit_price), whole(reorder, "reorder level"))
item.moves.append(f"opening stock {item.qty}")
self.items[item.sku] = item
return item
def move(self, sku: str, qty: str, direction: int, note: str) -> Item:
item, amount = self.get(sku), whole(qty, "quantity")
if direction < 0 and amount > item.qty:
raise InventoryError(f"only {item.qty} {item.name} in stock, can't remove {amount}")
item.qty += direction * amount
item.moves.append(f"{'+' if direction > 0 else '-'}{amount}{' (' + note + ')' if note else ''} -> {item.qty}")
return item
def table(items: list[Item]) -> None:
print(f" {'SKU':<6}{'Item':<20}{'Qty':>5}{'Price':>10}{'Value':>12} Status")
for item in items:
status = "REORDER" if item.low else "ok"
print(f" {item.sku:<6}{item.name:<20}{item.qty:>5}{item.price:>10,.2f}{item.value:>12,.2f} {status}")
def run(inv: Inventory, words: list[str]) -> None:
command = words[0].lower()
if command == "add":
item = inv.add(*words[1:6])
print(f"Added {item.sku} {item.name}: {item.qty} @ {item.price:,.2f}")
elif command in ("in", "out"):
item = inv.move(words[1], words[2], 1 if command == "in" else -1, " ".join(words[3:]))
print(f"{item.sku} {item.name}: now {item.qty}")
if item.low:
print(f" Warning: {item.name} is at or below its reorder level ({item.reorder}).")
elif command == "price":
item = inv.get(words[1])
old, item.price = item.price, price(words[2])
item.moves.append(f"price {old:,.2f} -> {item.price:,.2f}")
print(f"{item.sku} price changed from {old:,.2f} to {item.price:,.2f}")
elif command == "report":
items = sorted(inv.items.values(), key=lambda i: i.sku)
table(items)
print(f" {len(items)} items, {sum(i.qty for i in items)} units, total value {sum(i.value for i in items):,.2f}")
elif command == "low":
low = sorted((i for i in inv.items.values() if i.low), key=lambda i: i.qty - i.reorder)
if low:
table(low)
else:
print(" Nothing needs reordering.")
elif command == "history":
item = inv.get(words[1])
for i, move in enumerate(item.moves, 1):
print(f" {i}. {move}")
else:
raise InventoryError("unknown command")
def main() -> None:
inv = Inventory()
print("Inventory Tracker")
while True:
line = ask("> ")
if line is None or line.lower() == "quit":
break
if not line:
continue
try:
run(inv, line.split())
except InventoryError as error:
print(f"Error: {error}")
except (IndexError, TypeError):
print("Error: missing arguments for that command")
if __name__ == "__main__":
main()

What each file does

main.py
The Item dataclass, the Inventory service with stock movements, the reports and the command loop.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Inventory Tracker
> add P100 Gel_Pen 120 15 40
Added P100 Gel Pen: 120 @ 15.00
> add N200 A4_Notebook 60 45.50 25
Added N200 A4 Notebook: 60 @ 45.50
> add S300 Stapler 12 180 5
Added S300 Stapler: 12 @ 180.00
> add P100 Duplicate 1 1 1
Error: SKU P100 already exists
> add E400 Eraser ten 5 20
Error: opening stock must be a positive whole number, not 'ten'
> out P100 90 school order
P100 Gel Pen: now 30
Warning: Gel Pen is at or below its reorder level (40).
> out N200 70
Error: only 60 A4 Notebook in stock, can't remove 70
> out N200 40 walk-in
N200 A4 Notebook: now 20
Warning: A4 Notebook is at or below its reorder level (25).
> in S300 3 supplier
S300 Stapler: now 15
> price S300 199
S300 price changed from 180.00 to 199.00
> out S300 11
S300 Stapler: now 4
Warning: Stapler is at or below its reorder level (5).
> in Z999 5
Error: unknown SKU Z999
> low
SKU Item Qty Price Value Status
P100 Gel Pen 30 15.00 450.00 REORDER
N200 A4 Notebook 20 45.50 910.00 REORDER
S300 Stapler 4 199.00 796.00 REORDER
> report
SKU Item Qty Price Value Status
N200 A4 Notebook 20 45.50 910.00 REORDER
P100 Gel Pen 30 15.00 450.00 REORDER
S300 Stapler 4 199.00 796.00 REORDER
3 items, 54 units, total value 2,156.00
> history P100
1. opening stock 120
2. -90 (school order) -> 30
> quit
Input
add P100 Gel_Pen 120 15 40
add N200 A4_Notebook 60 45.50 25
add S300 Stapler 12 180 5
add P100 Duplicate 1 1 1
add E400 Eraser ten 5 20
out P100 90 school order
out N200 70
out N200 40 walk-in
in S300 3 supplier
price S300 199
out S300 11
in Z999 5
low
report
history P100
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • A duplicate SKU and the quantity 'ten' are rejected.
  • Removing 70 notebooks fails because only 60 are in stock.
  • After the movements all three items are at or below their reorder level, and the stock is worth 2,156.00.

Common errors

Stock goes negative

Check the requested quantity against the current stock before subtracting.

Underscores appear in item names

Replace underscores with spaces when adding, as add() does.

Possible improvements

  • Load and save inventory as CSV
  • Track suppliers and purchase orders
  • Report the best-selling items by quantity sold

Additional challenges

  1. 1Add an 'adjust <sku> <qty> <reason>' command for stock counts.
  2. 2Compute how many days of stock remain from average daily sales.
  3. 3Support item categories and a value report per category.

Built and tested it yourself? Mark it to update your dashboard.