Tutorials / Python from Scratch / Project: build the expense tracker, part 1

Project: build the expense tracker, part 1

15 min read python
Course contents (15 lessons)
  1. Getting started
  2. Installing Python 3.13 and running your first script
  3. Variables and basic data types
  4. Text, numbers and user input
  5. Working with strings
  6. Numbers and arithmetic
  7. Input and output: talking to the user
  8. Making decisions and repeating work
  9. Making decisions with if, elif and else
  10. Loops: for, while, break and continue
  11. Collections of data
  12. Lists and tuples
  13. Dictionaries and sets
  14. Functions and modules
  15. Writing your own functions
  16. Modules, pip and virtual environments
  17. Files and errors
  18. Reading and writing files
  19. Errors and exceptions
  20. Final project: expense tracker
  21. Project: build the expense tracker, part 1
  22. Project: summaries, search and improvements

What we are building

For the last two lessons we build one real program: a command-line expense tracker. You will be able to add an expense, list all expenses and see totals per category. Data is saved in a JSON file, so it is still there tomorrow.

It uses nearly everything from this course: input, conditionals, loops, lists, dictionaries, functions, files and error handling. Type the code yourself instead of pasting it. You learn far more that way.

Plan first

Before writing code, decide the pieces. I always do this on paper first, even for a small script.

  • An expense is a dictionary: {"date": "2025-03-14", "category": "food", "amount": 450.0, "note": "lunch"}.
  • All expenses live in a list.
  • The list is saved to expenses.json and loaded when the program starts.
  • Small functions do each job: load, save, ask for a number, add, list.

Keeping data loading and saving separate from user interaction is a good habit. It means you can change one without breaking the other.

The code so far

Create tracker.py:

import json
from datetime import date
from pathlib import Path

DATA_FILE = Path(__file__).parent / "expenses.json"


def load_expenses():
    """Return the saved expenses, or an empty list if there are none."""
    try:
        with open(DATA_FILE, encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return []
    except json.JSONDecodeError:
        print("Warning: expenses.json is damaged. Starting with an empty list.")
        return []


def save_expenses(expenses):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(expenses, f, indent=2)


def ask_amount(prompt):
    """Ask until the user enters a positive number."""
    while True:
        text = input(prompt).strip()
        try:
            amount = float(text)
        except ValueError:
            print("Please type a number, for example 450 or 99.5.")
            continue
        if amount <= 0:
            print("The amount must be more than zero.")
            continue
        return amount


def add_expense(expenses):
    category = input("Category (food, transport, bills...): ").strip().lower()
    if not category:
        category = "other"
    amount = ask_amount("Amount: ")
    note = input("Note (optional): ").strip()

    expenses.append({
        "date": date.today().isoformat(),
        "category": category,
        "amount": amount,
        "note": note,
    })
    save_expenses(expenses)
    print("Saved.")


def list_expenses(expenses):
    if not expenses:
        print("No expenses yet.")
        return
    print(f"{'#':>3}  {'Date':<10}  {'Category':<10}  {'Amount':>10}  Note")
    print("-" * 52)
    for number, e in enumerate(expenses, start=1):
        print(f"{number:>3}  {e['date']:<10}  {e['category']:<10}  "
              f"{e['amount']:>10.2f}  {e['note']}")
    total = sum(e["amount"] for e in expenses)
    print("-" * 52)
    print(f"{'Total':>26}  {total:>10.2f}")


def main():
    expenses = load_expenses()
    while True:
        print("\n1) Add expense   2) List expenses   q) Quit")
        choice = input("Choose: ").strip().lower()
        if choice == "1":
            add_expense(expenses)
        elif choice == "2":
            list_expenses(expenses)
        elif choice == "q":
            print("Goodbye.")
            break
        else:
            print("Please choose 1, 2 or q.")


if __name__ == "__main__":
    main()

Walking through it

At the top we build the path to expenses.json next to the script, so the program works no matter which folder you run it from. load_expenses handles two failures: no file yet (normal on the first run) and a damaged file. In both cases it returns an empty list instead of crashing.

ask_amount is the retry loop from the errors lesson. continue sends us back to ask again. Only a valid, positive number reaches the return.

add_expense builds one dictionary, appends it to the list and saves immediately. Saving after every change is simple and safe: if the program is closed unexpectedly, nothing is lost. date.today().isoformat() gives a string like 2025-03-14. This format sorts correctly as text.

In list_expenses, the format codes align the columns. The expression sum(e["amount"] for e in expenses) adds all amounts. It is a generator expression, a compact kind of loop that you will learn properly in the intermediate course. For now, read it as "the sum of the amount of each expense".

Finally main runs the menu loop. The if __name__ == "__main__": guard means the menu starts only when you run the file directly.

Try a session

1) Add expense   2) List expenses   q) Quit
Choose: 1
Category (food, transport, bills...): Food
Amount: 450
Note (optional): lunch
Saved.

Mistakes to watch for

  • If you see KeyError, check that the dictionary keys in list_expenses match those in add_expense exactly. A typo like "ammount" is easy to make.
  • If your data vanishes, check that you did not open the file with "a" or forget to call save_expenses.
  • Remember that quotes inside f-strings must differ from the outer quotes. That is why we use e['date'] inside a double-quoted f-string. Python 3.12 and later relax this rule, but the habit keeps your code readable on older versions too.

Try it yourself

Run the program and add four or five expenses in two or three categories. Open expenses.json in your editor and read how the data looks. Then add a menu option 3 that deletes an expense by its number. You will need to validate the number against the length of the list. We will use this exercise as a starting point in the next lesson.

python
import json
from datetime import date
from pathlib import Path

DATA_FILE = Path(__file__).parent / "expenses.json"


def load_expenses():
    """Return the saved expenses, or an empty list if there are none."""
    try:
        with open(DATA_FILE, encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return []
    except json.JSONDecodeError:
        print("Warning: expenses.json is damaged. Starting with an empty list.")
        return []


def save_expenses(expenses):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(expenses, f, indent=2)


def ask_amount(prompt):
    """Ask until the user enters a positive number."""
    while True:
        text = input(prompt).strip()
        try:
            amount = float(text)
        except ValueError:
            print("Please type a number, for example 450 or 99.5.")
            continue
        if amount <= 0:
            print("The amount must be more than zero.")
            continue
        return amount


def add_expense(expenses):
    category = input("Category (food, transport, bills...): ").strip().lower()
    if not category:
        category = "other"
    amount = ask_amount("Amount: ")
    note = input("Note (optional): ").strip()

    expenses.append({
        "date": date.today().isoformat(),
        "category": category,
        "amount": amount,
        "note": note,
    })
    save_expenses(expenses)
    print("Saved.")


def list_expenses(expenses):
    if not expenses:
        print("No expenses yet.")
        return
    print(f"{'#':>3}  {'Date':<10}  {'Category':<10}  {'Amount':>10}  Note")
    print("-" * 52)
    for number, e in enumerate(expenses, start=1):
        print(f"{number:>3}  {e['date']:<10}  {e['category']:<10}  "
              f"{e['amount']:>10.2f}  {e['note']}")
    total = sum(e["amount"] for e in expenses)
    print("-" * 52)
    print(f"{'Total':>26}  {total:>10.2f}")


def main():
    expenses = load_expenses()
    while True:
        print("\n1) Add expense   2) List expenses   q) Quit")
        choice = input("Choose: ").strip().lower()
        if choice == "1":
            add_expense(expenses)
        elif choice == "2":
            list_expenses(expenses)
        elif choice == "q":
            print("Goodbye.")
            break
        else:
            print("Please choose 1, 2 or q.")


if __name__ == "__main__":
    main()

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account