Module 12 · Lesson 02
Project: Personal Expense Tracker
Build an expense tracker class that validates each entry, totals spending by category and month, and saves its records to a CSV file so they survive between runs.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- One class owns the rules
- Group spending by category
- Save to CSV and load back
- Watch the totals add up
The tracker in four parts
One class owns the list of expenses and the rules for adding to it. The rest of the program asks the class.
The data
Each expense is a date, a category and an amount.
One door in
Every expense goes through
add(), which checks it and raises a custom exception if it is wrong.Summaries
A dictionary adds up the spending per category or per month.
Save and load
Write the records to CSV, and turn the text back into dates and floats when loading.
Trackers everywhere
The same idea, records plus rules plus summaries, is behind many money apps.
- Budget appsShow how much went on food this month.
- TravelAdd up a trip's costs and split them between friends.
- Pocket moneyTrack what you save and spend each week.
- Business toolsExpense reports group spending by month and by category.
Saving one expense
This line writes one expense into the CSV file. Tap each part to see its job.
Part 1 of 7
CSV writer:Made with csv.writer(f) on a file opened with newline="".
Build the tracker in five steps
Build the project one step at a time. Each example runs on its own: change it, then press Run.
Example 1 of 61. The data
Each expense is a small dictionary with a real date, a category and an amount.
Your turn: Add a cinema ticket for 9.0 on 12 April 2026.
from datetime import date
expenses = [
{"on": date(2026, 3, 2), "cat": "food", "amount": 12.5},
{"on": date(2026, 3, 9), "cat": "bus", "amount": 3.2},
{"on": date(2026, 4, 1), "cat": "food", "amount": 7.25},
]
for e in expenses:
print(e["on"], e["cat"], e["amount"])Press Run to see what it prints.Watch the totals add up
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- totals = {}
- records = [("food", 4.5), ("bus", 2.0), ("food", 3.0)]
- for cat, amount in records:
- totals[cat] = totals.get(cat, 0) + amount
- biggest = max(totals, key=totals.get)
- print(totals)
- print("Most on", biggest)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Money with two decimals:
print(f"${3.5:.2f}")0 of 6 answered
Common tracker misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
date.fromisoformat("2024-03-15") # text -> date
e.day.strftime("%Y-%m") # month key
totals[k] = totals.get(k, 0) + amount # group and add
raise ExpenseError("message") from None # clear error
csv.writer(f).writerow([...]) # save a row
for row in csv.DictReader(f): float(row["amount"]) # load and convertPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A month of spending
Build the tracker, add a few expenses including two bad ones, and print the total and the per-category and per-month summaries.
from datetime import date
CATEGORIES = {"food", "transport", "home", "fun"}
class ExpenseError(Exception):
pass
class Expense:
def __init__(self, day, category, amount, note=""):
self.day, self.category, self.amount, self.note = day, category, amount, note
class Tracker:
def __init__(self):
self.expenses = []
def add(self, day_text, category, amount, note=""):
try:
day = date.fromisoformat(day_text)
except ValueError:
raise ExpenseError(f"bad date {day_text!r}") from None
if category not in CATEGORIES:
raise ExpenseError(f"unknown category {category!r}")
if amount <= 0:
raise ExpenseError(f"amount must be positive, got {amount}")
self.expenses.append(Expense(day, category, round(amount, 2), note))
def total(self):
return round(sum(e.amount for e in self.expenses), 2)
def by(self, key):
totals = {}
for e in self.expenses:
k = key(e)
totals[k] = round(totals.get(k, 0) + e.amount, 2)
return dict(sorted(totals.items()))
t = Tracker()
entries = [
("2024-03-02", "food", 23.40), ("2024-03-05", "transport", 12.00),
("2024-03-31", "fun", 18.50), ("2024-04-01", "food", 31.10),
("2024-02-30", "food", 5.00), ("2024-04-03", "pets", 9.99),
]
for day, category, amount in entries:
try:
t.add(day, category, amount)
except ExpenseError as error:
print("Rejected:", error)
print("Total:", t.total())
print("By category:", t.by(lambda e: e.category))
print("By month:", t.by(lambda e: e.day.strftime("%Y-%m")))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Appending to the list from outside the class
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
t = Tracker()
t.expenses.append(('2024-01-01', 'food', -50))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Corporate finance
Team travel claims
A small company collects travel claims from staff as a CSV export. Finance checks each claim against a per-category limit and totals the approved claims per person before payday.
Why Python fits
The same pattern as the tracker: read rows, convert types, apply rules, group totals in a dictionary. Claims in unknown categories or over the limit are collected for a person to review instead of being silently paid or silently dropped.
Pythonimport csv LIMITS = {"train": 150, "hotel": 120, "meal": 40} with open("claims.csv", "w", newline="", encoding="utf-8") as f: f.write("name,category,amount\nAna,train,89.50\nAna,meal,52.00\nBen,hotel,110.00\nBen,taxi,30.00\nAna,hotel,95.00\n") approved, flagged = {}, [] with open("claims.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): amount = float(row["amount"]) limit = LIMITS.get(row["category"]) if limit is None or amount > limit: flagged.append(f"{row['name']} {row['category']} {amount:.2f}") else: approved[row["name"]] = approved.get(row["name"], 0) + amount for name in sorted(approved): print(f"Pay {name}: {approved[name]:.2f}") print("Needs review:", flagged)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Why not store amounts as text with a currency sign?
Should I use CSV or JSON for the save file?
How do I avoid float rounding problems with money?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 6 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.