An expense tracker turns raw entries into useful summaries. You will record expenses, validate amounts, total by category, and report the largest expense.
What you will build#
A program that:
- Records an expense with a description, amount, and category.
- Lists all expenses.
- Prints a total.
- Prints totals per category.
- Finds the largest single expense.
- Rejects negative or non-numeric amounts.
Data model#
expenses = [
{"description": "Coffee", "amount": 4.50, "category": "food"},
{"description": "Bus pass", "amount": 32.00, "category": "transport"},
{"description": "Lunch", "amount": 12.75, "category": "food"},
]Amounts are floats for learning purposes. For real money, store integer cents to avoid binary floating-point rounding. The display logic can convert cents to pounds or dollars.
Reading an amount safely#
def read_amount(prompt):
text = input(prompt).strip()
try:
amount = float(text)
except ValueError:
print("Enter a number.")
return None
if amount <= 0:
print("Amount must be positive.")
return None
return round(amount, 2)round() keeps the stored value tidy, but it does not make float arithmetic exact. Keep that limitation in mind and format only at display time.
Adding an expense#
category = input("Category: ").strip().lower()
if not category:
print("Category is required.")
continue
description = input("Description: ").strip()
amount = read_amount("Amount: ")
if amount is None or not description:
print("Expense not added.")
continue
expenses.append({
"description": description,
"amount": amount,
"category": category,
})
print("Expense added.")Totals#
total = sum(expense["amount"] for expense in expenses)
print(f"Total: {total:.2f}")Grouping by category uses a dictionary:
totals_by_category = {}
for expense in expenses:
category = expense["category"]
totals_by_category[category] = totals_by_category.get(category, 0) + expense["amount"]
for category in sorted(totals_by_category):
print(f"{category.title():<12} {totals_by_category[category]:.2f}")The <12 format specifier left-aligns the category in a 12-character field, producing a neat table. Very long category names will exceed the field width, which is acceptable.
Largest expense#
largest = max(expenses, key=lambda expense: expense["amount"])
print(f"Largest: {largest['description']} ({largest['amount']:.2f})")If the list is empty, max() raises ValueError. Check if not expenses: first.
Filtering by category#
wanted = input("Category to view: ").strip().lower()
matching = [expense for expense in expenses if expense["category"] == wanted]
print(f"{len(matching)} matching expenses")
for expense in matching:
print(f"- {expense['description']}: {expense['amount']:.2f}")This is a linear scan. For a small personal tracker, that is appropriate. A database would index the category.
A useful report#
Combine the pieces into a function:
def print_report(expenses):
if not expenses:
print("No expenses recorded.")
return
total = sum(expense["amount"] for expense in expenses)
average = total / len(expenses)
largest = max(expenses, key=lambda expense: expense["amount"])
print(f"Expenses: {len(expenses)}")
print(f"Total: {total:.2f}")
print(f"Average: {average:.2f}")
print(f"Largest: {largest['description']} ({largest['amount']:.2f})")Testing checklist#
- Add three expenses across two categories.
- Verify the total equals the sum of the amounts.
- Check per-category totals.
- Try a negative amount, zero, and text.
- Print the report with no expenses.
- Check that the largest expense is correct when two amounts tie.
Stretch goals#
- Add a monthly budget and warn when spending exceeds it.
- Support an optional date and group by month.
- Save entries as JSON and load them with validation.
- Add a text search over descriptions.
- Convert the program to use integer cents and compare the results for
0.1 + 0.2.
