Project: Expense Tracker
Let's build a useful command-line program that records your spending in a CSV file and shows a monthly summary. It uses functions, dataclasses, files, dates, dictionaries and error handling.
This project is a small but real program, organised the way professional code is: data in a dataclass, separate functions for adding, loading and summarising, error handling for bad input, and a main() function. Read it top to bottom, then run it on your computer and try the challenges - building on existing code is exactly what most programming jobs involve.
Example
import csv
from dataclasses import dataclass
from datetime import date
from pathlib import Path
from collections import defaultdict
FILE = Path("expenses.csv")
FIELDS = ["day", "category", "amount", "note"]
@dataclass
class Expense:
day: date
category: str
amount: float
note: str = ""
def load() -> list[Expense]:
if not FILE.exists():
return []
with FILE.open(newline="", encoding="utf-8") as f:
return [Expense(date.fromisoformat(r["day"]), r["category"], float(r["amount"]), r["note"])
for r in csv.DictReader(f)]
def save(expenses: list[Expense]) -> None:
with FILE.open("w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=FIELDS)
w.writeheader()
for e in expenses:
w.writerow({"day": e.day.isoformat(), "category": e.category, "amount": e.amount, "note": e.note})
def summary(expenses: list[Expense], year: int, month: int) -> dict[str, float]:
totals: dict[str, float] = defaultdict(float)
for e in expenses:
if e.day.year == year and e.day.month == month:
totals[e.category] += e.amount
return dict(sorted(totals.items(), key=lambda kv: kv[1], reverse=True))
def main() -> None:
expenses = load()
while True:
choice = input("\n1) Add 2) Month summary 3) Quit: ").strip()
if choice == "1":
try:
amount = float(input("Amount (₹): "))
except ValueError:
print("Please type a number.")
continue
category = input("Category (food, travel, bills...): ").strip().lower() or "other"
note = input("Note: ").strip()
expenses.append(Expense(date.today(), category, amount, note))
save(expenses)
print("Saved ✓")
elif choice == "2":
today = date.today()
totals = summary(expenses, today.year, today.month)
if not totals:
print("No expenses this month yet.")
for cat, amt in totals.items():
print(f"{cat:<10} ₹{amt:>10,.2f}")
print(f"{'TOTAL':<10} ₹{sum(totals.values()):>10,.2f}")
elif choice == "3":
break
if __name__ == "__main__":
main()Try the summary logic
Example
Challenges
- Add a monthly budget per category and warn when you go over it.
- Export a chart with the matplotlib library.
- Write pytest tests for
summary(). - Turn it into a small web app with Flask or FastAPI.
if __name__ == "__main__": runs main() only when you start this file directly, not when another file imports it (for example, your tests).📝 Test yourself
1. Why does load() check FILE.exists() first?
2. What does defaultdict(float) give for a missing key?
3. Fill in the check that runs main() only when the file is started directly:
if __name__ == "":
main()
