8. Final Capstone Project
Capstone Project: Persistent CLI Expense Tracker
Put everything from earlier modules together to build a clean, menu-driven Expense Tracker in Python that validates inputs, summarizes spending by category, and saves to JSON.
- Combine functions, loops, dicts, try/except, and JSON into a full CLI app
- Persist user expenses across sessions in expenses.json
- Verify category summary logic with automated assert checks
Congratulations on making it to the final lesson! Now let's combine everything you learned—variables, input(), if/else, while and for loops, lists, dictionaries, functions, JSON files, try/except, and unit tests—into one real, useful app you can run in your terminal.
What We Are Building
Our CLI Expense Tracker will:
- Load any previously saved expenses from
expenses.jsonwhen it starts. - Show a repeating menu until you pick Exit:
1— Add a new expense (name, category, amount, today's date)2— View all saved expenses3— See total spending broken down by category4— Exit
- Handle typos safely with
try/exceptso bad inputs never crash your program.
How the Code Is Organized (Before You Read It)
Instead of cramming 90 lines into one giant loop, we split the app into 5 small, single-job functions:
load_expenses()→ readsexpenses.json(or returns[]on first run)save_expenses(expenses)→ writes the list toexpenses.jsonadd_expense(expenses)→ asks the user, validates the price, appends a dict, and savesview_expenses(expenses)→ prints each numbered expense nicelyshow_summary(expenses)→ uses a dictionary to sum totals per categorymain()→ runs thewhile True:menu loop
Complete Code (expense_tracker.py)
Create a file named expense_tracker.py on your computer and paste this code:
import json
from datetime import date
from pathlib import Path
DATA_FILE = Path("expenses.json")
def load_expenses():
if not DATA_FILE.exists():
return []
try:
with open(DATA_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, OSError):
print("Warning: Could not read expenses.json. Starting fresh.")
return []
def save_expenses(expenses):
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(expenses, f, indent=2)
def add_expense(expenses):
title = input("Item description: ").strip()
if not title:
print("Description cannot be empty.")
return
category = input("Category (Food, Travel, Study, Other): ").strip().title()
if not category:
category = "Other"
try:
amount = float(input("Amount ($): "))
if amount <= 0:
print("Amount must be greater than zero.")
return
except ValueError:
print("Please enter numbers only (example: 12.50).")
return
entry = {
"title": title,
"category": category,
"amount": round(amount, 2),
"date": date.today().isoformat(),
}
expenses.append(entry)
save_expenses(expenses)
print(f"Saved: {title} (${amount:.2f})")
def view_expenses(expenses):
if not expenses:
print("\nNo expenses recorded yet.")
return
print("\n--- All Expenses ---")
for idx, item in enumerate(expenses, start=1):
print(
f"{idx}. [{item['date']}] {item['title']} "
f"({item['category']}) — ${item['amount']:.2f}"
)
def show_summary(expenses):
if not expenses:
print("\nNothing to summarize yet.")
return
total = 0.0
by_category = {}
for e in expenses:
total += e["amount"]
cat = e["category"]
by_category[cat] = by_category.get(cat, 0.0) + e["amount"]
print("\n--- Spending Summary ---")
for cat, cat_total in by_category.items():
print(f"• {cat}: ${cat_total:.2f}")
print(f"Total Spent: ${total:.2f}")
def main():
expenses = load_expenses()
print("=== Yadav Academy Expense Tracker ===")
while True:
print("\n1. Add Expense 2. View All 3. Summary 4. Exit")
choice = input("Choose an option (1-4): ").strip()
if choice == "1":
add_expense(expenses)
elif choice == "2":
view_expenses(expenses)
elif choice == "3":
show_summary(expenses)
elif choice == "4":
print("Goodbye! Your data is saved in expenses.json.")
break
else:
print("Please enter 1, 2, 3, or 4.")
if __name__ == "__main__":
main()Run it from your terminal:
python3 expense_tracker.pyIt tells Python: "Only run main() if the user executed this file directly." If another file imports load_expenses later, main() won't start unexpectedly.
Practice & Bonus Upgrades
Capstone Completion & Bonus Upgrades
0/4 doneTest Your Capstone Summary Logic Live (assert)
Before finishing, verify the category-summary helper right inside your browser just like a pytest suite:
Click “Run Code” to execute this snippet right in your browser.
You've finished all 20 lessons of Python Fundamentals! Take the Final Assessment below to test what you learned and unlock your printable certificate.