A small project: expense tracker
1 / 9A small project: expense tracker
Time to build something real: a program that remembers what you spent and adds it up by category.
About 50 lines in two files. Every piece comes from the maps before this one: variables, collections, decisions, loops, functions, modules and a class.
In this topic
The plan
Like building with bricks you already own. First decide what the program does, then cut it into small jobs.
Four commands, typed by the user:
adda new expenselistall of themtotalsper categoryquit
One function per command, plus one class that describes a single expense.
expenses.py: the class and the functionsmain.py: the menu that uses them
Write one piece, run it, see it work, then add the next. Never write everything first and test at the end.
Step 1: one expense
A receipt: one object holds everything about one purchase. This goes into expenses.py.
class Expense:
def __init__(self, amount, category, note):
self.amount = amount
self.category = category
self.note = note
Inside the class:
def line(self):
return f"{self.amount:.2f} {self.category}: {self.note}"
:.2f inside an f-string shows a number with two decimals.
lunch = Expense(4.5, "food", "lunch")
print(lunch.line())
Prints 4.50 food: lunch.
Class, __init__, self, attributes and a method, return, an f-string, and the types float and str.
Step 2: add an expense
The receipts go into a drawer: one list that holds every Expense object.
def add_expense(expenses):
amount = float(input("Amount? "))
category = input("Category? ")
note = input("Note? ")
expenses.append(Expense(amount, category, note))
input() always gives text. float(...) turns "4.5" into 4.5, so it can be added up later.
The function does not own the list. It gets it as an argument and appends to it, so the caller sees the new item.
input(), converting with float(), variables, a function with a parameter, creating an object, append on a list.
Step 3: show and add up
Go through the drawer receipt by receipt: once to print them, once to sort the amounts into piles.
def show(expenses):
if not expenses:
print("Nothing yet.")
for expense in expenses:
print(expense.line())
An empty list counts as False, so if not expenses: catches the empty drawer.
def totals(expenses):
result = {}
for expense in expenses:
if expense.category in result:
result[expense.category] = result[expense.category] + expense.amount
else:
result[expense.category] = expense.amount
return result
The category is the key, the running sum is the value. A new category starts a pile; a known one makes its pile higher.
Result: {"food": 7.7, "travel": 12.0}
for over a list, if and else, in, empty means False, a dictionary, calling a method, return.
Step 4: the menu
A waiter who keeps coming back: ask what the user wants, do it, ask again, until they say quit. This goes into main.py.
def main():
expenses = []
while True:
choice = input("add, list, totals or quit? ")
if choice == "add":
add_expense(expenses)
elif choice == "list":
show(expenses)
elif choice == "totals":
for category, amount in totals(expenses).items():
print(f"{category}: {amount:.2f}")
elif choice == "quit":
break
else:
print("I do not know that one.")
The loop would run for ever. break is the only way out, and it is reached when the user types quit.
.items() hands out each key and value as a tuple. for category, amount in ... unpacks it into two names.
while, break, if/elif/else, ==, a list created once and passed around, tuple unpacking, f-strings.
Step 5: join and run
Plug the two files together: main.py borrows what expenses.py offers.
First line of main.py:
from expenses import add_expense, show, totals
Last lines of main.py:
if __name__ == "__main__":
main()
Then, in the terminal: python main.py
add, list, totals or quit? add
Amount? 4.5
Category? food
Note? lunch
add, list, totals or quit? list
4.50 food: lunch
add, list, totals or quit? totals
food: 4.50
add, list, totals or quit? quit
Your own module, from ... import, the run-or-import check, running a .py file.
Make it yours
The program works, and it is yours to extend. Each idea below is one small step.
Put every category into a set and ask for its len(). Duplicates disappear by themselves.
Type abc as the amount and the program stops with a ValueError. Find out how try and except let it ask again.
Everything is lost when the program ends. Save the expenses to a file and load them at the start.
Add a fifth command. Show the list with numbers, ask which one, and take it out.
git init, then one commit per finished step. Now every experiment is safe to try.