Final project: build a personal expense tracker
Bring the whole Python course together: build a menu-driven expense tracker that validates input, saves to a CSV file and prints a spending summary, with milestones, a rubric and a worked solution.
🎯 By the end of this project you will be able to:
- Plan a complete program and build it in small, tested milestones
- Combine loops, decisions, functions, dictionaries, files and error handling
- Check your work against a rubric and compare it with a worked solution
Outline
The brief
You are going to build a program you can genuinely use: a personal expense tracker that runs in the terminal or IDLE. It keeps your expenses in a CSV file, so they are still there next time you run it, and it tells you where your money goes.
Your finished program must:
- Load existing expenses from
expenses.csvwhen it starts, and still work if the file does not exist yet. - Show a menu: 1) Add expense 2) List expenses 3) Summary 4) Quit, and keep showing it until the user chooses Quit.
- Add an expense with a date, category, description and amount. A blank date means today. Bad dates and amounts that are not positive numbers must be rejected with a helpful message, and the user asked again.
- Save each new expense to the CSV file straight away.
- List every expense in neat columns.
- Print a summary with the total for each category, its share of all spending as a percentage, and the grand total.
| Skill | Where you learned it | Used for |
|---|---|---|
while True menu with break | Lesson 9 | The main menu |
Functions with return | Lesson 10 | One function per job |
| Dictionaries and totals per key | Lesson 11 | Each expense; the summary |
csv.DictReader / writing in "a" mode | Lesson 12 | Loading and saving |
try / except and retry loops | Lesson 13 | Validating dates and amounts |
datetime and pathlib | Lesson 14 | Today's date; checking the file exists |
Starter materials
Create a new folder, for example expense-tracker, and download the sample data into it. It already has 7 expenses so you can test the list and summary straight away.
⬇ Download expenses.csvStarter data with the columns date, category, description and amount.
Then create tracker.py in the same folder with this skeleton. Each pass is a placeholder (a line that does nothing) for you to replace:
import csv
from datetime import date
from pathlib import Path
FILENAME = "expenses.csv"
FIELDS = ["date", "category", "description", "amount"]
def load_expenses():
pass # Milestone 2: return a list of expense dictionaries
def save_expense(expense):
pass # Milestone 3: append one expense to the CSV file
def add_expense(expenses):
pass # Milestone 3
def show_expenses(expenses):
pass # Milestone 2
def show_summary(expenses):
pass # Milestone 4
def main():
pass # Milestone 1: the menu loop
main()Milestones
Build the program in five small steps. Run it after every step and check it does what the step says before moving on. Small steps mean that when something breaks, you know it was the last few lines you wrote.
| Milestone | What to build | Done when |
|---|---|---|
| 1. Menu | In main(), a while True loop that prints the menu, reads a choice and uses if/elif to call the right function. Option 4 prints Goodbye and breaks. Any other answer prints a hint. | You can type 2, 3, 9 and 4 and the program reacts correctly, then ends. |
| 2. Load and list | load_expenses() reads the CSV with csv.DictReader, converts each amount with float() and returns a list. show_expenses() prints each one in columns. | Option 2 prints the 7 starter expenses. Renaming the CSV does not crash the program. |
| 3. Add and save | add_expense() asks for the four fields, builds a dictionary, calls save_expense() and appends it to the list. save_expense() opens the file in "a" mode and writes one row. | A new expense appears in option 2 and is still there after you quit and run the program again. |
| 4. Summary | show_summary() totals each category with a dictionary (lesson 11), then prints each category's total and percentage share and the grand total. | The totals match what you get with a calculator. |
| 5. Validation and polish | Write ask_amount() and ask_date() with retry loops (lesson 13). Handle an empty category. Add a docstring or comment to each function. | Typing abc, -5 or 12/11/2026 gives a helpful message and asks again. |
Test your program
Before you look at the solution, run through this test script. Type exactly these answers, one per line:
3(summary of the starter data: the grand total should be 2795.25)1, then the date12/11/2026(should be rejected), then2026-11-12, categorystudy, descriptionPython book, amountabc(rejected),-5(rejected), then4502(8 expenses listed, the new one last)3(Study is now 660.00 and the grand total 3245.25)7(should ask you to type 1 to 4), then4to quit
Worked solution
Try to finish all five milestones before opening the solution. There are many correct ways to write this program; yours does not need to match line for line. Compare how each job is split into functions and how errors are handled.
Your turn
Compare with the worked solution
Open this when you have finished, or when you have been stuck on one milestone for more than 20 minutes.
Show the solution
import csv
from datetime import date
from pathlib import Path
FILENAME = "expenses.csv"
FIELDS = ["date", "category", "description", "amount"]
def load_expenses():
"""Read every expense from the CSV file into a list of dictionaries."""
expenses = []
try:
with open(FILENAME, newline="") as file:
for row in csv.DictReader(file):
row["amount"] = float(row["amount"])
expenses.append(row)
except FileNotFoundError:
print(f"No {FILENAME} yet. It will be created when you add an expense.")
return expenses
def save_expense(expense):
"""Add one expense to the end of the CSV file, writing the header if the file is new."""
is_new_file = not Path(FILENAME).exists()
with open(FILENAME, "a", newline="") as file:
writer = csv.DictWriter(file, fieldnames=FIELDS)
if is_new_file:
writer.writeheader()
writer.writerow(expense)
def ask_date():
"""Ask for a date; a blank answer means today."""
while True:
text = input("Date (YYYY-MM-DD, blank for today): ").strip()
if text == "":
return date.today().isoformat()
try:
return date.fromisoformat(text).isoformat()
except ValueError:
print("Please use the format YYYY-MM-DD, for example 2026-11-25.")
def ask_amount():
"""Keep asking until the user types a number greater than zero."""
while True:
try:
amount = float(input("Amount: "))
except ValueError:
print("Please type a number, like 250 or 99.50.")
continue
if amount > 0:
return amount
print("The amount must be more than zero.")
def add_expense(expenses):
expense_date = ask_date()
category = input("Category (for example Food, Transport, Bills): ").strip().title()
if category == "":
category = "Other"
description = input("Description: ").strip()
amount = ask_amount()
expense = {"date": expense_date, "category": category, "description": description, "amount": amount}
save_expense(expense)
expenses.append(expense)
print(f"Saved: {description} ({amount:.2f})")
def show_expenses(expenses):
if len(expenses) == 0:
print("No expenses yet.")
return
for e in expenses:
print(f"{e['date']} {e['category']:<10} {e['description']:<22} {e['amount']:>9.2f}")
print(f"{len(expenses)} expenses")
def show_summary(expenses):
if len(expenses) == 0:
print("No expenses yet.")
return
totals = {}
for e in expenses:
totals[e["category"]] = totals.get(e["category"], 0) + e["amount"]
grand_total = sum(totals.values())
print(f"{'Category':<12}{'Total':>10}{'Share':>8}")
for category in sorted(totals):
share = totals[category] / grand_total * 100
print(f"{category:<12}{totals[category]:>10.2f}{share:>7.1f}%")
print(f"{'All':<12}{grand_total:>10.2f}")
def main():
expenses = load_expenses()
print(f"Loaded {len(expenses)} expenses from {FILENAME}.")
while True:
print()
print("1) Add expense 2) List expenses 3) Summary 4) Quit")
choice = input("Choose: ").strip()
if choice == "1":
add_expense(expenses)
elif choice == "2":
show_expenses(expenses)
elif choice == "3":
show_summary(expenses)
elif choice == "4":
print("Goodbye!")
break
else:
print("Please type 1, 2, 3 or 4.")
main()Output (you type: 3, 1, 12/11/2026, 2026-11-12, study, Python book, abc, -5, 450, 2, 3, 7, 4)
Loaded 7 expenses from expenses.csv. 1) Add expense 2) List expenses 3) Summary 4) Quit Choose: 3 Category Total Share Bills 299.00 10.7% Food 1636.25 58.5% Study 210.00 7.5% Transport 650.00 23.3% All 2795.25 1) Add expense 2) List expenses 3) Summary 4) Quit Choose: 1 Date (YYYY-MM-DD, blank for today): 12/11/2026 Please use the format YYYY-MM-DD, for example 2026-11-25. Date (YYYY-MM-DD, blank for today): 2026-11-12 Category (for example Food, Transport, Bills): study Description: Python book Amount: abc Please type a number, like 250 or 99.50. Amount: -5 The amount must be more than zero. Amount: 450 Saved: Python book (450.00) 1) Add expense 2) List expenses 3) Summary 4) Quit Choose: 2 2026-11-01 Food Groceries 850.50 2026-11-02 Transport Metro card top-up 500.00 2026-11-03 Food Lunch with friends 420.00 2026-11-05 Bills Mobile recharge 299.00 2026-11-07 Study Notebook and pens 210.00 2026-11-08 Transport Auto rickshaw 150.00 2026-11-10 Food Vegetables and fruit 365.75 2026-11-12 Study Python book 450.00 8 expenses 1) Add expense 2) List expenses 3) Summary 4) Quit Choose: 3 Category Total Share Bills 299.00 9.2% Food 1636.25 50.4% Study 660.00 20.3% Transport 650.00 20.0% All 3245.25 1) Add expense 2) List expenses 3) Summary 4) Quit Choose: 7 Please type 1, 2, 3 or 4. 1) Add expense 2) List expenses 3) Summary 4) Quit Choose: 4 Goodbye!
How to get there: main() only handles the menu; every other job has its own small function, so each can be read and tested on its own. load_expenses() converts amounts to numbers once, when reading, so the rest of the program can do maths safely. New expenses are appended to the file immediately, so nothing is lost if the program is closed suddenly. Validation lives in ask_date() and ask_amount(), which loop until the input is usable. The output above is exactly what the test script produces with the starter data.
Make it your own
Finished? Pick one or more of these extensions. Each one practises a skill you will use in real projects:
- Add a monthly filter: ask for a month such as
2026-11and show only expenses whose date starts with it (e["date"].startswith(month)). - Add a budget per category in a dictionary and warn when a category goes over budget.
- Add delete last expense, rewriting the whole CSV file in
"w"mode from the list. - Sort the summary by total, highest first. Search for “Python sorted key” and read about the
keyargument. - Move the helper functions into a module called
storage.pyand import it (lesson 14).
Recap
- You planned a complete program and built it in five tested milestones.
- You combined loops, decisions, functions, dictionaries, CSV files and error handling in one program.
- Small single-purpose functions make programs easier to read, test and extend.
- Saving data to a file as soon as it changes keeps it safe between runs.
Check your understanding
Answer all 3 questions, then check your answers to see an explanation for each one.
1. Why does the tracker save each expense to the file as soon as it is added, rather than only when the user quits?
2. Why does `load_expenses()` convert `amount` with `float()` straight after reading?
3. Which file mode does `save_expense()` use, and why?
Self-check and complete the course
Tick every rubric item to complete the project.