Show contents
Chapter 6 of 7 · 20 min
Project: an expense tracker
By the end of this chapter, you'll be able to
- Split a problem into small functions that each have one job
- Represent data with a list of dictionaries
- Check your functions with assert
- Assemble the functions into a program that produces a report
The specification
The expenses are a list of dictionaries {"label": ..., "amount": ..., "category": ...}. The program must provide:
add(expenses, label, amount, category): adds an expense, refuses a negative or zero amount;total(expenses): the sum of the amounts;by_category(expenses): a dictionary{category: total};biggest(expenses): the expense with the highest amount, orNoneif there is none;report(expenses): a summary text.
Method: write one function at a time, and test it straight away before moving on to the next.
Testing with assert
assert condition does nothing if the condition is true, and raises an AssertionError otherwise. It's the simplest possible test:
def total(expenses):
return round(sum(e["amount"] for e in expenses), 2)
assert total([]) == 0
assert total([{"label": "bread", "amount": 1.2, "category": "groceries"}]) == 1.2
print("total tests: OK")
total tests: OK
sum(e["amount"] for e in expenses) adds up one value per expense: it's the same idea as a list comprehension, without the square brackets.
The loop is over: we return the dictionary of totals.
Text description of the animation
- Three expenses: bus 2 (transport), rice 8 (groceries), taxi 5 (transport). We want a total per category.
- We start from an empty dictionary.
- Expense 1: the key transport doesn't exist, get returns 0. We store 2.
- Expense 2: a new key groceries, with 8.
- Expense 3: transport already exists, we add 5 to 2.
- The loop is over: we return the dictionary of totals.
The complete program
def add(expenses, label, amount, category):
if amount <= 0:
raise ValueError("The amount must be positive")
expenses.append({"label": label, "amount": amount, "category": category})
def total(expenses):
return round(sum(e["amount"] for e in expenses), 2)
def by_category(expenses):
totals = {}
for e in expenses:
cat = e["category"]
totals[cat] = round(totals.get(cat, 0) + e["amount"], 2)
return totals
def biggest(expenses):
if not expenses:
return None
return max(expenses, key=lambda e: e["amount"])
def report(expenses):
lines = [f"Total: {total(expenses)} €"]
for cat, amount in sorted(by_category(expenses).items()):
lines.append(f"- {cat}: {amount} €")
top = biggest(expenses)
if top:
lines.append(f"Biggest expense: {top['label']} ({top['amount']} €)")
return "\n".join(lines)
# Tests
month = []
assert biggest(month) is None
add(month, "Bus", 2, "transport")
add(month, "Rice", 8.5, "groceries")
add(month, "Taxi", 5, "transport")
assert total(month) == 15.5
assert by_category(month) == {"transport": 7, "groceries": 8.5}
assert biggest(month)["label"] == "Rice"
try:
add(month, "Mistake", -3, "misc")
assert False, "a negative amount should have been refused"
except ValueError:
pass
print(report(month))
Total: 15.5 €
- groceries: 8.5 €
- transport: 7 €
Biggest expense: Rice (8.5 €)
Three new things, useful every day:
raise ValueError("...")raises an error on purpose when a piece of data is invalid;try/except ValueErrorlets you catch it;max(expenses, key=lambda e: e["amount"])looks for the maximum according to a criterion:lambda e: e["amount"]is a small anonymous function that gives the amount of an expense;"\n".join(lines)joins a list of texts, separating them with a line break.
Your turn
Project: improve the expense trackerPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: over budget
Write a function alerts(expenses, budgets) that receives a dictionary of budgets per category (for example {"transport": 6, "groceries": 20}) and returns the sorted list of categories whose total goes over the budget. A category without a budget is never in alert.
Hint 1
by_category: don't compute the totals yourself again.Hint 2
budgets.get(cat) returns None if the category has no budget: test that case before comparing.Show the solution and common mistakes
def by_category(expenses):
totals = {}
for e in expenses:
totals[e["category"]] = totals.get(e["category"], 0) + e["amount"]
return totals
def alerts(expenses, budgets):
result = []
for cat, amount in by_category(expenses).items():
budget = budgets.get(cat)
if budget is not None and amount > budget:
result.append(cat)
return sorted(result)
expenses = [
{"label": "Bus", "amount": 2, "category": "transport"},
{"label": "Taxi", "amount": 5, "category": "transport"},
{"label": "Rice", "amount": 8.5, "category": "groceries"},
{"label": "Cinema", "amount": 7, "category": "leisure"},
]
assert alerts(expenses, {"transport": 6, "groceries": 20}) == ["transport"]
assert alerts([], {"transport": 6}) == []
print(alerts(expenses, {"transport": 6, "groceries": 20}))
['transport']
Common mistakes:
- Writing
if amount > budgets[cat]: a category without a budget (leisure) causes aKeyError. - Comparing with
>=: an expense exactly equal to the budget doesn't go over it.
Summary
- 1A program is split into small functions that each have a single job.
- 2assert checks a condition and reports precisely what's wrong.
- 3raise raises an error for invalid data; try/except lets you handle it.
- 4Test each function as soon as it's written, before moving on.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.