Project: summaries, search and improvements
Course contents (15 lessons)
- Getting started
- Installing Python 3.13 and running your first script
- Variables and basic data types
- Text, numbers and user input
- Working with strings
- Numbers and arithmetic
- Input and output: talking to the user
- Making decisions and repeating work
- Making decisions with if, elif and else
- Loops: for, while, break and continue
- Collections of data
- Lists and tuples
- Dictionaries and sets
- Functions and modules
- Writing your own functions
- Modules, pip and virtual environments
- Files and errors
- Reading and writing files
- Errors and exceptions
- Final project: expense tracker
- Project: build the expense tracker, part 1
- 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.strptimeand catchValueError. - Add a monthly budget per category and warn when it is passed.
- Export a month to CSV with the
csvmodule. - Move the functions into modules:
storage.pyfor loading and saving,reports.pyfor summaries. - Keep money in whole paisa (integers) to avoid float rounding issues, or use the
decimalmodule.
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"]).
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