Python Mini Project
In this project you'll build a small expense tracker, one step at a time. It brings together much of the course: dataclasses, lists and dictionaries, functions, string formatting, error handling, match and JSON.
By the end, the tracker understands commands like these:
add 12.50 food Lunch with team
add 45 transport Monthly bus pass
report
undo
saveEvery step is a complete program that you can run and modify. Because the playgrounds can't wait for keyboard input, the "user" is simulated by a list of command strings — in a real terminal app you would read them with input() in a loop.
Step 1: Model one expense
An expense has an amount, a category, a description and a date. A dataclass gives us a constructor and a readable printout for free. We store money as integer cents, which avoids floating-point rounding problems.
from dataclasses import dataclass
from datetime import date
@dataclass
class Expense:
cents: int
category: str
note: str
day: date
@property
def amount(self):
return self.cents / 100
def __str__(self):
return f"{self.day} {self.category:<10} {self.amount:>8.2f} {self.note}"
lunch = Expense(1250, "food", "Lunch with team", date(2025, 5, 2))
print(lunch)
print(lunch.amount)2025-05-02 food 12.50 Lunch with team
12.5
Step 2: A tracker that holds many expenses
The Tracker class keeps a list of expenses and offers methods to add them and compute totals. A helper converts text like "12.50" into cents and rejects bad values.
from dataclasses import dataclass
from datetime import date
@dataclass
class Expense:
cents: int
category: str
note: str
day: date
def __str__(self):
return f"{self.day} {self.category:<10} {self.cents / 100:>8.2f} {self.note}"
def parse_cents(text):
value = round(float(text) * 100)
if value <= 0:
raise ValueError("amount must be positive")
return value
class Tracker:
def __init__(self):
self.expenses = []
def add(self, amount_text, category, note, day):
expense = Expense(parse_cents(amount_text), category.lower(), note, day)
self.expenses.append(expense)
return expense
def total_cents(self):
return sum(e.cents for e in self.expenses)
t = Tracker()
t.add("12.50", "Food", "Lunch with team", date(2025, 5, 2))
t.add("45", "transport", "Monthly bus pass", date(2025, 5, 3))
t.add("3.20", "food", "Coffee", date(2025, 5, 3))
for e in t.expenses:
print(e)
print(f"Total: {t.total_cents() / 100:.2f}")2025-05-02 food 12.50 Lunch with team
2025-05-03 transport 45.00 Monthly bus pass
2025-05-03 food 3.20 Coffee
Total: 60.70
Step 3: Reports by category
Now let's summarise spending per category, sorted from largest to smallest, with a simple text bar chart. A dictionary accumulates the totals.
expenses = [
("food", 1250), ("transport", 4500), ("food", 320),
("fun", 1800), ("food", 2100), ("transport", 600),
]
def category_totals(items):
totals = {}
for category, cents in items:
totals[category] = totals.get(category, 0) + cents
return totals
def print_report(totals):
grand = sum(totals.values())
print(f"{'Category':<10} {'Amount':>8} {'Share':>6}")
for category, cents in sorted(totals.items(), key=lambda kv: kv[1], reverse=True):
share = cents / grand
bar = "#" * round(share * 20)
print(f"{category:<10} {cents / 100:>8.2f} {share:>6.0%} {bar}")
print(f"{'TOTAL':<10} {grand / 100:>8.2f}")
print_report(category_totals(expenses))Category Amount Share
transport 51.00 48% ##########
food 36.70 35% #######
fun 18.00 17% ###
TOTAL 105.70
Step 4: A command interpreter
Next we turn text commands into actions. match on the split command makes the parser short and readable, and try/except keeps one bad command from crashing the whole program.
def handle(command, expenses):
match command.split(maxsplit=3):
case ["add", amount, category, note]:
cents = round(float(amount) * 100)
if cents <= 0:
raise ValueError("amount must be positive")
expenses.append((category, cents, note))
return f"added {category} {cents / 100:.2f}"
case ["add", *_]:
raise ValueError("usage: add <amount> <category> <note>")
case ["undo"]:
if not expenses:
return "nothing to undo"
category, cents, note = expenses.pop()
return f"removed '{note}'"
case ["total"]:
return f"total {sum(c for _, c, _ in expenses) / 100:.2f}"
case _:
raise ValueError(f"unknown command: {command!r}")
script = [
"add 12.50 food Lunch with team",
"add 45 transport Monthly bus pass",
"add abc food Cake",
"add -3 food Refund?",
"add 9.99",
"undo",
"fly to the moon",
"total",
]
expenses = []
for command in script:
try:
print(">", command, "->", handle(command, expenses))
except ValueError as err:
print(">", command, "-> error:", err)> add 12.50 food Lunch with team -> added food 12.50
> add 45 transport Monthly bus pass -> added transport 45.00
> add abc food Cake -> error: could not convert string to float: 'abc'
> add -3 food Refund? -> error: amount must be positive
> add 9.99 -> error: usage: add <amount> <category> <note>
> undo -> removed 'Monthly bus pass'
> fly to the moon -> error: unknown command: 'fly to the moon'
> total -> total 12.50
split(maxsplit=3) splits at most three times, so a note with spaces like Lunch with team stays in one piece.
Step 5: Saving and loading with JSON
To keep data between runs, convert the expenses to JSON. asdict() turns a dataclass into a dictionary; dates need converting to ISO strings and back. Here we round-trip through a JSON string — in a real app you'd write it to a file with json.dump().
import json
from dataclasses import dataclass, asdict
from datetime import date
@dataclass
class Expense:
cents: int
category: str
note: str
day: date
def to_json(expenses):
rows = [{**asdict(e), "day": e.day.isoformat()} for e in expenses]
return json.dumps(rows, indent=1)
def from_json(text):
return [Expense(r["cents"], r["category"], r["note"], date.fromisoformat(r["day"]))
for r in json.loads(text)]
original = [
Expense(1250, "food", "Lunch", date(2025, 5, 2)),
Expense(4500, "transport", "Bus pass", date(2025, 5, 3)),
]
saved = to_json(original)
print(saved)
restored = from_json(saved)
print(restored == original)
print(restored[1])[
{
"cents": 1250,
"category": "food",
"note": "Lunch",
"day": "2025-05-02"
},
{
"cents": 4500,
"category": "transport",
"note": "Bus pass",
"day": "2025-05-03"
}
]
True
Expense(cents=4500, category='transport', note='Bus pass', day=datetime.date(2025, 5, 3))
Step 6: The complete tracker
Finally, everything in one program. The ExpenseTracker class holds the data, run() interprets commands, and a fixed "today" date keeps the output reproducible.
import json
from dataclasses import dataclass, asdict
from datetime import date
@dataclass
class Expense:
cents: int
category: str
note: str
day: date
class ExpenseTracker:
def __init__(self, today):
self.today = today
self.expenses = []
self.saved = None
def add(self, amount, category, note):
cents = round(float(amount) * 100)
if cents <= 0:
raise ValueError("amount must be positive")
self.expenses.append(Expense(cents, category.lower(), note, self.today))
return f"Added {cents / 100:.2f} to {category.lower()}"
def report(self):
totals = {}
for e in self.expenses:
totals[e.category] = totals.get(e.category, 0) + e.cents
lines = [f" {c:<10}{v / 100:>8.2f}"
for c, v in sorted(totals.items(), key=lambda kv: -kv[1])]
lines.append(f" {'TOTAL':<10}{sum(totals.values()) / 100:>8.2f}")
return "\n".join(lines)
def save(self):
self.saved = json.dumps([{**asdict(e), "day": e.day.isoformat()}
for e in self.expenses])
return f"Saved {len(self.expenses)} expenses ({len(self.saved)} bytes)"
def run(self, command):
match command.split(maxsplit=3):
case ["add", amount, category, note]:
return self.add(amount, category, note)
case ["report"]:
return self.report()
case ["undo"] if self.expenses:
return f"Removed '{self.expenses.pop().note}'"
case ["undo"]:
return "Nothing to undo"
case ["save"]:
return self.save()
case _:
raise ValueError("unknown command")
tracker = ExpenseTracker(today=date(2025, 5, 10))
commands = [
"add 12.50 Food Lunch with team",
"add 45 transport Monthly bus pass",
"add 18 fun Cinema",
"add 7.25 food Groceries",
"add 3 food Mistake",
"undo",
"dance",
"report",
"save",
]
for command in commands:
print(f"> {command}")
try:
print(tracker.run(command))
except ValueError as err:
print(f"Error: {err}")> add 12.50 Food Lunch with team
Added 12.50 to food
> add 45 transport Monthly bus pass
Added 45.00 to transport
> add 18 fun Cinema
Added 18.00 to fun
> add 7.25 food Groceries
Added 7.25 to food
> add 3 food Mistake
Added 3.00 to food
> undo
Removed 'Mistake'
> dance
Error: unknown command
> report
transport 45.00
food 19.75
fun 18.00
TOTAL 82.75
> save
Saved 4 expenses (329 bytes)
Make it your own
Ideas for extending the tracker:
| Idea | Skills practised |
|---|---|
Real interactive loop with input() and a quit command |
while loops, user input |
Save to and load from expenses.json on disk |
file handling, with |
report food shows only one category |
match patterns, filtering |
| Monthly budgets with warnings when exceeded | dictionaries, comparisons |
add with an optional date: add 5 food Tea 2025-05-01 |
parsing, date.fromisoformat |
Unit tests for add and report |
the unittest module |
Tip: Keep the "logic" (the tracker class) separate from the "interface" (where commands come from). That's what let us test everything here with a simple list of strings — and it's what lets you later swap in a web or GUI interface.
Test yourself
Why does the tracker store money as integer cents?
- Integers use less memory
- To avoid floating-point rounding errors in sums
- JSON can't store floats
- Dataclasses only allow ints
What does "add 5 food Hot tea".split(maxsplit=3) return?
- ['add', '5', 'food', 'Hot', 'tea']
- ['add', '5', 'food', 'Hot tea']
- ['add 5 food', 'Hot tea']
- ['add', '5 food Hot tea']
Why are the example commands stored in a list instead of read with input()?
- input() doesn't exist in Python 3
- So the program runs without waiting for a keyboard and the output is reproducible
- Lists are faster than input()
- match only works on lists