Skip to contentSkip to navigation

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

Tap any part of the code below, or press Next.1 of 7 explored

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.

Python
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"])
Output
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.

  1. totals = {}
  2. records = [("food", 4.5), ("bus", 2.0), ("food", 3.0)]
  3. for cat, amount in records:
  4. totals[cat] = totals.get(cat, 0) + amount
  5. biggest = max(totals, key=totals.get)
  6. print(totals)
  7. 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 notesOpen

Building the tracker

The brief

The tracker keeps a list of expenses. Each expense has a date, a category from a fixed list (food, transport, home, fun), an amount and an optional note. The program must reject bad entries with a clear message: a negative amount, an unknown category or a date that does not exist. It must report the total, the total per category and the total per month, and it must save everything to a CSV file and load it again later.

Choosing the data

Each expense is a small record. A dictionary with four keys would work, but this project uses a tiny class, so every expense has exactly the same attributes and prints clearly:

Try it 1: edit me, then Run
from datetime import date

class Expense:
    def __init__(self, day, category, amount, note=""):
        self.day = day
        self.category = category
        self.amount = amount
        self.note = note

    def __repr__(self):
        return f"Expense({self.day.isoformat()}, {self.category}, {self.amount:.2f})"
Output
Press Run to see what it prints.

The date is stored as a date object, not as text, so it can be compared, sorted and grouped by month without any string slicing. Amounts are floats rounded to two places when shown. Real accounting software uses whole numbers of cents, or the decimal module, to avoid tiny float rounding errors; for a personal tracker, rounding on display is enough.

One class owns the rules

A second class, Tracker, holds the list and every rule about it. Other code never appends to the list directly; it calls add, so validation can never be skipped:

Try it 2: edit me, then Run
CATEGORIES = {"food", "transport", "home", "fun"}

class ExpenseError(Exception):
    pass

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))
Output
Press Run to see what it prints.

Each problem raises the same ExpenseError with a precise message, so the caller needs only one except. raise ... from None hides the original ValueError from the traceback, because the new message already says everything a user needs.

Summaries

Every summary walks the list once and adds amounts into a dictionary keyed by what you are grouping on:

Try it 3: edit me, then Run
    def total(self):
        return round(sum(e.amount for e in self.expenses), 2)

    def by_category(self):
        totals = {}
        for e in self.expenses:
            totals[e.category] = round(totals.get(e.category, 0) + e.amount, 2)
        return totals

    def by_month(self):
        totals = {}
        for e in self.expenses:
            key = e.day.strftime("%Y-%m")
            totals[key] = round(totals.get(key, 0) + e.amount, 2)
        return dict(sorted(totals.items()))
Output
Press Run to see what it prints.

Formatting the date as 2024-03 gives a key that sorts in time order, because ISO-style text sorts the same way as the dates it describes.

Saving and loading

CSV suits this data: one row per expense, and the file opens in any spreadsheet. Saving writes the date in ISO form; loading converts each field back to its proper type and sends it through add, so a file edited by hand is validated too:

Try it 4: edit me, then Run
import csv

    def save(self, path):
        with open(path, "w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["date", "category", "amount", "note"])
            for e in self.expenses:
                writer.writerow([e.day.isoformat(), e.category, f"{e.amount:.2f}", e.note])

    def load(self, path):
        with open(path, newline="", encoding="utf-8") as f:
            for row in csv.DictReader(f):
                self.add(row["date"], row["category"], float(row["amount"]), row["note"])
Output
Press Run to see what it prints.

A round trip, saving and then loading into a fresh tracker, should give the same totals. That makes a perfect test.

Showing a report

The summaries return dictionaries, which keeps them easy to test. Turning them into something pleasant to read is a separate job for a report method that builds lines of text. Format-string widths line the columns up: f"{category:<10}{amount:>8.2f}" pads the category to ten characters on the left and right-aligns the amount in eight, with two decimals. Sorting categories by amount, largest first, puts the biggest spending at the top, which is usually what people want to see first. Keeping the report separate from the calculations also means the same numbers can later be shown in a web page or a chart without touching the maths.

Testing as you build

Build in this order and check each step before moving on: Expense and its repr; add with one good entry and each kind of bad entry; total; the two summaries with three or four expenses across two months; save, looking at the file; and finally load into a new tracker and compare totals. The Lab tasks below follow the same path.

Ideas to extend it

Add a monthly budget per category and warn when spending passes it, export the summaries to JSON for a chart, or add a remove method that deletes an expense by its position in a sorted list.

Syntax

The general shape of the statements in this lesson.

syntax.py
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 convert
Output
Press 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

Intermediate

Build the tracker, add a few expenses including two bad ones, and print the total and the per-category and per-month summaries.

Python
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")))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The two bad entries, a date that does not exist and an unknown category, are rejected with precise messages, and the rest are stored. One by method with a key function replaces two nearly identical summary methods: the lambda decides what to group on, exactly as with sorted.

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.

Buggy code: run it
t = Tracker()
t.expenses.append(('2024-01-01', 'food', -50))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

A negative expense is stored and every total is wrong

Write this instead

t = Tracker()
t.add('2024-01-01', 'food', 50.0)

Why it happens

Code outside the class bypasses add, so the validation never runs.

In the real world

Where this shows up in software people use every day.

  1. Team travel claims

    Corporate finance

    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.

    Python
    import 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)
    Output
    Press 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?

Text cannot be added or compared as money. Store plain numbers and add the currency sign only when printing.

Should I use CSV or JSON for the save file?

CSV, because each expense is a flat row and you may want to open it in a spreadsheet. If expenses later gain nested data, such as a list of receipt items, switch to JSON.

How do I avoid float rounding problems with money?

Round when showing totals, as this project does. For real accounting, store whole cents as integers or use the decimal module, which represents amounts like 0.10 exactly.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.