Skip to the workspace
Pebellslearn by building
Fundamentals Follow-up Projects  ›  Capstone Project

Project 3 — Expense & Budget Tracker

Capstone Project 50 minA budget tracker groups spending and compares it with planned limits.

A budget tracker groups spending and compares it with planned limits.

Accumulate expenses by category, identify overspending and produce summaries that explain where the money went.

The final category total and the first time it crossed a threshold are different facts. Build the monthly report from totals, then replay expenses to produce alerts. Refunds will test whether your program remembers current state separately from notifications it has already emitted.

Three zones — under 80%, the warning band, over the limit — with an expense climbing through them; the 80% alert fires once and a later crossing of the same line stays silent

A monthly total answers how much was spent. An alert answers when a threshold was first crossed. Those are different questions: a refund can erase a final overspend while leaving the earlier warning part of the month's history.

In this project you build that tracker in two layers. First, a monthly report: total spend, spend per category, which categories went over, and the biggest one. Then the part that makes it useful, the alerts: replay the month one expense at a time and warn the first time each category nears or passes its limit.

Here's a month of spending against budgets of food: 100 and fun: 50, and what the finished tracker says:

day expense tracker says
2 food 45 —
9 fun 42 day 9: fun at 80% of budget
12 food 40 day 12: food at 80% of budget
20 fun 15 day 20: fun over budget by $7.00
end total $142.00, 1 over budget

Every box is live — edit and ▶ Run.


The plan

An expense is a small dict: {"category": "food", "amount": 45} (the alerts add a "day"). Budgets are one dict, {category: limit}. Everything the tracker knows comes from folding the list of expenses into running totals:

Drawing diagram…

The practice cards below build the report's pieces — add_up, by_category, over_budget, top_category. The Your task editor assembles them into monthly_report. The alerts are the project at the bottom.


Preparing this topic’s interactive investigation…

Milestone 1 — totals and the tally

The grand total is one generator expression. The per-category total is the pattern you'll use more than any other in data work: tally into a dict.

python

Why totals.get(category, 0) + amount and not the shorter +=?

What happens when this runs?
totals = {}
totals["food"] += 5
print(totals)

Milestone 2 — who went over?

A category is over when its spend exceeds its limit. But what about a category with no budget at all — gifts, say? The cleanest answer is to give it an infinite limit, which nothing can exceed:

What does this print?
spent = {"rent": 900, "food": 80, "gifts": 500}
budgets = {"rent": 800, "food": 100}
print(sorted(c for c, a in spent.items() if a > budgets.get(c, float("inf"))))

float("inf") is positive infinity, a float greater than every finite real number. It is not greater than itself, and NaN has different comparison rules. It's a neat way to say "no limit" without a special case.


Milestone 3 — the biggest category

max over a dict iterates its keys; key= says compare them by their totals. And a month with no spending has no biggest category:

broken — fix itValueError

Run it and read the error. Make an empty month return None instead of crashing.

Put the four together and you have monthly_report, the Your task editor. A report you read deserves aligned columns, and f-strings do alignment for free — :<8 pads left-aligned to 8 characters, :>8.2f right-aligns a number with two decimals:

python

Change 130 to 99 and run it again — the OVER disappears and every column still lines up.


What can be reordered safely?

For exact amounts, rearranging expenses within a month leaves category totals unchanged: addition gathers the same contributions. In these exercises, amounts are simple numeric inputs; a real currency system should define cent rounding explicitly. Adding a category with no budget still changes grand total and possibly the biggest category, but cannot make it “over.”

Useful report checks follow from the data relationships: the sum of category totals should match the grand total; every name in over must have a budget; spending exactly the limit must stay out of over. The largest single expense need not belong to the largest-total category.

Alerts are order-sensitive. [+120, -40] against a limit of 100 emits an over-budget event, while [-40, +120] does not, although both finish at 80. The input contract supplies date order; sorting just the final totals cannot recover the event history.

Milestone 4 — alerts while it matters

The report looks at the finished month. Alerts replay it in order, keeping a running total per category, and speak the moment a line is crossed. Two lines matter:

  • 80% of the limit — a warning: day 12: food at 80% of budget.
  • over the limit — day 20: fun over budget by $7.00.

Each alert fires once per category. A tracker that repeats "food is at 80%" with every sandwich is a tracker people mute. So besides the running totals, the program remembers which alerts it has already given — a set is perfect for "have I seen this before?". Step through a short month:

step through it
1budgets = {"fun": 50}
2spent, warned, out = {}, set(), []
3for day, amount in [(3, 30), (9, 12), (15, 5)]:
4 spent["fun"] = spent.get("fun", 0) + amount
5 if spent["fun"] >= 0.8 * budgets["fun"] and "fun" not in warned:
6 warned.add("fun")
7 out.append(f"day {day}: fun at 80% of budget")
8print(out)

Day 9 takes fun to 42, past the 40 line, so it warns. Day 15 takes it to 47 — still at least 80% — but fun is already in warned, so it stays quiet.

The full rule has one more wrinkle, and it's worth taking slowly:

Deciding which alert, if any, one expense firesStep 1 of 6
  1. Update the running total first

    spent[cat] = spent.get(cat, 0) + amount. Every check below is about the total after this expense. A refund is just a negative amount; it lowers the total the same way.


A current fact is different from an event that happened

Keep spent for the current balance and warned/over for events already emitted. Against a budget of 50, the sequence +60, -20, +15 gives:

After amount Current spent Has an over alert happened? Emit now?
+60 60 yes over by 10
-20 40 yes nothing
+15 55 yes nothing

The set named over therefore means ever alerted over, not currently over. Reusing its length for the month-end summary would be wrong after a refund. Recompute current overspending from spent and budgets instead. A category belongs to warned after an over event because that stronger event also satisfies the warning obligation.

This is a small state machine with a policy: each alert type occurs at most once per category per run. It assumes finite numeric amounts and meaningful budgets. A zero budget needs an explicit interpretation of “80%”: its threshold is also zero, not an ordinary percentage-progress display.

Before changing the re-arm policy below, write expected messages for an overspend, refund, then second overspend. Explain which set must shrink under your new rule, and which facts must remain as an audit history. That separates a deliberate behavior change from an accidental repeat notification.

Build the alerts

The starter includes B, a budget dict, and E(day, category, amount), a shortcut that builds an expense dict so the tests stay readable. Keep both.

practice projectBudget alerts

Write alerts(expenses, budgets). Each expense is {"day", "category", "amount"}, in date order; amounts can be negative (refunds). Return a list of lines:

  • the first time a category's running total is at least 80% of its limit: day 12: food at 80% of budget;
  • the first time it goes over the limit: day 20: fun over budget by $7.00. If one expense crosses both lines, only the over-budget alert is given.
  • Each alert fires at most once per category. Categories without a budget never alert.
  • Last line, always: total $142.00, 1 over budget — total of all spending, and how many categories are over their limit at the end.
  • an empty month
  • under 80%: quiet
  • exactly 80% warns
  • a warning fires once
  • over, by how much
  • one big jump: only the worse alert
  • no budget, no alerts
  • refunds don't re-fire alerts
  • the summary uses the final totals
  • the month from the top of the page

Once it passes, try a policy question the tests don't settle: after a refund takes a category back under its limit, should a later overspend alert again? Change the code to re-arm the alert, and decide which behaviour you'd want on your own phone.


🎯 Your turn

Build the four practice cards, then write monthly_report(expenses, budgets) in the editor beside the lesson:

  • food 120 + gas 30 + food 10, budgets {"food": 100, "gas": 50} → {"total": 160, "by_category": {"food": 130, "gas": 30}, "over": ["food"], "top": "food"}
  • no expenses → {"total": 0, "by_category": {}, "over": [], "top": None}

Press ▶ Run, try the scenario chips, and hit ✓ Check. ✅

Your task
Build monthly_report(expenses, budgets): tally spend per category, then return {"total", "by_category", "over": the sorted categories whose spend exceeds their budget (a category with no budget is never over), "top": the biggest-spend category, or None for an empty month}.

Practice — level up

0/4 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

BuildStep 1 — Total spend

An expense is {"category": str, "amount": number}. Write add_up(expenses) returning the total of every amount. An empty list totals 0.

dict-accesssum
BuildStep 2 — Group by category

Write by_category(expenses) returning {category: total_spent} — every expense's amount added into its category's running total. Note that totals[cat] += amount crashes the first time a category appears.

setdefault/getloop
BossStep 3 — Over budget

Given spent {category: amount} and budgets {category: limit}, write over_budget(spent, budgets) returning the alphabetically sorted categories whose spend exceeds their limit. Spending exactly the limit is not over, and a category with no budget is never over.

dictcomprehensionsorted
BossStep 4 — Biggest category

Write top_category(expenses) returning the category with the highest total spend across all its expenses (or None for no expenses). Many small expenses can beat one big one.

groupmax-keyguard
Project context and further resources
monthly_report.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
monthly_report(expenses, budgets) → dictTally spending by category, compare against budgets, and report
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.