Tutorials / Python from Scratch / Project: summaries, search and improvements

Project: summaries, search and improvements

14 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

Extending what you built

You now have a tracker that adds and lists expenses. A tracker is only useful if it answers questions, such as "how much did I spend on food this month?" In this lesson we add three features: totals by category, a month filter, and deleting an entry. Then I will suggest next steps.

Totals by category

This is the dictionary counting pattern from earlier, except we add amounts instead of counting words.

def totals_by_category(expenses):
    totals = {}
    for e in expenses:
        category = e["category"]
        totals[category] = totals.get(category, 0) + e["amount"]
    return totals


def show_summary(expenses):
    if not expenses:
        print("No expenses yet.")
        return
    totals = totals_by_category(expenses)
    grand_total = sum(totals.values())
    ranked = sorted(totals.items(), key=lambda pair: pair[1], reverse=True)
    for category, amount in ranked:
        share = amount / grand_total * 100
        print(f"{category:<12} {amount:>10.2f}  {share:5.1f}%")
    print(f"{'Total':<12} {grand_total:>10.2f}")

The function returns a dictionary and does no printing, so it is easy to reuse. show_summary sorts the pairs so the biggest category comes first. The key=lambda pair: pair[1] part says "sort by the second item of each pair", which is the amount. A lambda is a tiny unnamed function written in one line. If it looks strange, you can write a normal def that returns pair[1] and pass its name instead.

Filtering by month

Our dates are strings like 2025-03-14. The first seven characters, 2025-03, identify the month, so a string method does the job.

def expenses_for_month(expenses, month):
    """month is a string such as '2025-03'."""
    return [e for e in expenses if e["date"].startswith(month)]

The square brackets with a for inside make a list comprehension. It reads: "a list of every e from expenses where the date starts with the month". It is a shorter way to write a loop that builds a list. You can pass the result to show_summary to get a monthly report.

def monthly_report(expenses):
    month = input("Month (YYYY-MM): ").strip()
    selected = expenses_for_month(expenses, month)
    if not selected:
        print("Nothing recorded for that month.")
        return
    show_summary(selected)

Deleting an expense

Here is a possible solution to last lesson's exercise.

def delete_expense(expenses):
    list_expenses(expenses)
    if not expenses:
        return
    text = input("Number to delete (or press Enter to cancel): ").strip()
    if not text:
        return
    try:
        index = int(text) - 1
    except ValueError:
        print("That is not a number.")
        return
    if not 0 <= index < len(expenses):
        print("No expense with that number.")
        return
    removed = expenses.pop(index)
    save_expenses(expenses)
    print(f"Deleted {removed['category']} {removed['amount']:.2f}.")

We subtract one because the list on screen starts at 1 but Python lists start at 0. This kind of off-by-one conversion is where bugs love to hide, so test the first and last numbers by hand.

Updating the menu

Add the new options inside main:

        print("\n1) Add  2) List  3) Summary  4) Month report  5) Delete  q) Quit")
        choice = input("Choose: ").strip().lower()
        if choice == "1":
            add_expense(expenses)
        elif choice == "2":
            list_expenses(expenses)
        elif choice == "3":
            show_summary(expenses)
        elif choice == "4":
            monthly_report(expenses)
        elif choice == "5":
            delete_expense(expenses)
        elif choice == "q":
            break

Testing your own program

After adding a feature, try to break it. Type letters where numbers are expected. Press Enter on empty answers. Delete the JSON file and start again. Put garbage text in the JSON file and see what happens. Testing like this finds more bugs than reading your code over again.

Ideas for taking it further

  • Let the user type a date for an expense instead of always using today. Use datetime.strptime and catch ValueError.
  • Add a monthly budget per category and warn when it is passed.
  • Export a month to CSV with the csv module.
  • Move the functions into modules: storage.py for loading and saving, reports.py for summaries.
  • Keep money in whole paisa (integers) to avoid float rounding issues, or use the decimal module.

Where to go next

You can now read and write real Python programs, which is a solid base. The next step is learning how Python programs are structured as they grow: comprehensions, generators, classes, type hints and tests. The intermediate and advanced course on this site covers all of those. In the meantime, build something that you personally need. A program you care about teaches you more than any exercise.

Try it yourself

Add a "search" option that asks for a word and prints every expense whose note or category contains it, ignoring upper and lower case. Then add an option that shows the single largest expense. Use max(expenses, key=lambda e: e["amount"]).

python
def totals_by_category(expenses):
    totals = {}
    for e in expenses:
        category = e["category"]
        totals[category] = totals.get(category, 0) + e["amount"]
    return totals


def show_summary(expenses):
    if not expenses:
        print("No expenses yet.")
        return
    totals = totals_by_category(expenses)
    grand_total = sum(totals.values())
    ranked = sorted(totals.items(), key=lambda pair: pair[1], reverse=True)
    for category, amount in ranked:
        share = amount / grand_total * 100
        print(f"{category:<12} {amount:>10.2f}  {share:5.1f}%")
    print(f"{'Total':<12} {grand_total:>10.2f}")

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