Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Projects
  3. Build an Expense Tracker in Python

Project 5 · Guided build

Build an Expense Tracker in Python

Record expenses, group them by category, calculate totals, and find the largest spending category.

Open the compilerWarm-up exercises
intermediate75–90 minuteslists of dictionariesaggregationsortingformatting money
On this page
  1. What you will build
  2. Data model
  3. Reading an amount safely
  4. Adding an expense
  5. Totals
  6. Largest expense
  7. Filtering by category
  8. A useful report
  9. Testing checklist
  10. Stretch goals

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#

Python
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#

Python
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#

Python
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#

Python
total = sum(expense["amount"] for expense in expenses)
print(f"Total: {total:.2f}")

Grouping by category uses a dictionary:

Python
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#

Python
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#

Python
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:

Python
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.

Floats and money

0.1 + 0.2 is not exactly 0.3. For a learning project, formatting to two decimals hides most of the issue. For real financial software, use integer cents or decimal.Decimal and define rounding rules explicitly.

Previous projectBuild a Contact Book in PythonNext projectBuild a Password Generator in Python

On this page

  1. What you will build
  2. Data model
  3. Reading an amount safely
  4. Adding an expense
  5. Totals
  6. Largest expense
  7. Filtering by category
  8. A useful report
  9. Testing checklist
  10. Stretch goals

Project checklist

  • Read the requirements.
  • Plan the data model.
  • Build one feature at a time.
  • Test invalid input.
  • Refactor after it works.