Python ProgrammingBeginnerFree to access
Python Inventory Manager with File Persistence
Create a command-line inventory program that validates quantities, calculates stock values and later saves records to JSON.
Download free Markdown guideNo email, account or payment required · .md text format
What you will build
Practice Python functions, dictionaries, defensive input handling and simple persistence.
Before you begin
- Python 3.11 or newer
- Variables, collections, loops and functions
Local setup instructions
- Save the starter as inventory.py.
- Run python inventory.py in your terminal.
- After you understand the in-memory version, add load/save commands using pathlib and json.
Starter code
inventory.pyThis is a working starting example, not the finished project. Follow the setup above and complete each milestone to build your own solution.
from decimal import Decimal
products = {
"P001": {"name": "Notebook", "price": Decimal("150.00"), "quantity": 8}
}
def sell(sku: str, count: int) -> None:
if count <= 0:
raise ValueError("Quantity must be positive")
product = products.get(sku)
if product is None:
raise KeyError(f"Unknown SKU: {sku}")
if product["quantity"] < count:
raise ValueError("Insufficient stock")
product["quantity"] -= count
def stock_value() -> Decimal:
return sum(
(item["price"] * item["quantity"] for item in products.values()),
start=Decimal("0.00"),
)
sell("P001", 2)
print("Remaining stock value:", stock_value())Project build milestones
- Model products with SKU, name, price and quantity.
- Implement safe add, sell and restock functions with clear error messages.
- Calculate total inventory value from price times quantity.
- Load and save JSON to a local file and handle missing/corrupt files.
- Add unit tests for duplicate SKU and insufficient stock.
Completion checklist
Use these checks to self-review the finished project.
- The code rejects negative stock changes.
- Selling more stock than available raises a helpful error.
- Inventory totals are computed correctly.
- After persistence is implemented, restarting restores saved records.
Optional challenges
- Refactor inventory operations into a class with tests.
- Add a CSV import with defensive column/type validation.