Project: Budget Tracker
In this project you'll build a terminal budget tracker that records income and expenses, saves them to a file and prints a spending summary by category. It brings together functions, dictionaries, loops, input validation, exceptions and JSON files.
The goal
Many young people juggle pocket money, HELB loans, part-time pay and M-Pesa spending without knowing where the money actually goes. Our tracker will answer that question. It's a menu-driven program that keeps running until the user chooses to quit.
Features
- Add income or expenses with an amount, a category and an optional note.
- Reject invalid amounts (text, negatives, zero) without crashing.
- Save every transaction to
budget.json, so data survives between runs. - List all transactions and show totals, the balance and spending by category with percentages.
You'll need: dictionaries, functions, match-case, try/except and JSON. No third-party packages are required.
Step 1: Decide how to store the data
Each transaction is a dictionary, and the whole budget is a list of them. That shape converts directly to JSON:
{"date": "2026-03-14", "kind": "expense", "amount": 1500.0, "category": "transport", "note": "matatu fare"}
Using a list of dictionaries keeps the program simple and makes the saved file easy to read and even edit by hand.
Step 2: Loading, saving and validating
We need three helpers. load_transactions() reads the file if it exists and copes with a damaged file. save_transactions() writes the list back. ask_amount() keeps asking until the user types a positive number, accepting commas such as 25,000.
Step 3: The full program
Save this as budget_tracker.py and run it with python budget_tracker.py.
"""Kuza Budget Tracker: record income and spending in the terminal."""
import json
from collections import defaultdict
from datetime import date
from pathlib import Path
DATA_FILE = Path("budget.json")
def load_transactions():
"""Return the saved list of transactions, or an empty list."""
if not DATA_FILE.exists():
return []
try:
with DATA_FILE.open(encoding="utf-8") as file:
return json.load(file)
except json.JSONDecodeError:
print("Warning: budget.json is damaged, so starting a new budget.")
return []
def save_transactions(transactions):
with DATA_FILE.open("w", encoding="utf-8") as file:
json.dump(transactions, file, indent=2)
def ask_amount(prompt):
"""Keep asking until the user types a positive number."""
while True:
text = input(prompt).strip().replace(",", "")
try:
amount = float(text)
except ValueError:
print("Please enter a number, e.g. 1500 or 250.50")
continue
if amount <= 0:
print("The amount must be greater than zero.")
continue
return round(amount, 2)
def add_transaction(transactions, kind):
amount = ask_amount(f"Amount ({kind}) in KES: ")
category = input("Category (e.g. salary, food, rent): ").strip().lower() or "other"
note = input("Note (optional): ").strip()
transactions.append({
"date": date.today().isoformat(),
"kind": kind,
"amount": amount,
"category": category,
"note": note,
})
save_transactions(transactions)
print(f"Saved {kind} of KES {amount:,.2f} under '{category}'.")
def show_transactions(transactions):
if not transactions:
print("No transactions yet.")
return
for number, t in enumerate(transactions, start=1):
sign = "+" if t["kind"] == "income" else "-"
line = f"{number:>2}. {t['date']} {t['category']:<12} {sign}{t['amount']:>11,.2f} {t['note']}"
print(line.rstrip())
def show_summary(transactions):
income = sum(t["amount"] for t in transactions if t["kind"] == "income")
spent = sum(t["amount"] for t in transactions if t["kind"] == "expense")
print(f"Total income: KES {income:>12,.2f}")
print(f"Total expenses: KES {spent:>12,.2f}")
print(f"Balance: KES {income - spent:>12,.2f}")
by_category = defaultdict(float)
for t in transactions:
if t["kind"] == "expense":
by_category[t["category"]] += t["amount"]
if by_category:
print("\nSpending by category:")
ranked = sorted(by_category.items(), key=lambda item: item[1], reverse=True)
for category, total in ranked:
share = total / spent * 100
print(f" {category:<12} KES {total:>10,.2f} ({share:.0f}%)")
def main():
transactions = load_transactions()
print("=== Kuza Budget Tracker ===")
print(f"Loaded {len(transactions)} saved transaction(s).")
while True:
print("\n1) Add income 2) Add expense 3) View all 4) Summary 5) Quit")
choice = input("Choose an option: ").strip()
match choice:
case "1":
add_transaction(transactions, "income")
case "2":
add_transaction(transactions, "expense")
case "3":
show_transactions(transactions)
case "4":
show_summary(transactions)
case "5":
print("Goodbye! Your budget is saved in budget.json.")
break
case _:
print("Please choose a number from 1 to 5.")
if __name__ == "__main__":
main()
How the important parts work
- Validation:
ask_amount()usestry/except ValueErroraroundfloat(), andcontinuesends the loop back to ask again. The function only returns once the amount is valid. - Saving after every change: calling
save_transactions()insideadd_transaction()means nothing is lost if the user closes the window instead of choosing Quit. - Formatting: in
{t['category']:<12}the<12left-aligns text in 12 characters, and{t['amount']:>11,.2f}right-aligns a number in 11 characters with commas and two decimal places. That lines up the columns. - Grouping:
defaultdict(float)starts every new category at0.0, so we can add to it straight away. - Leaving the loop:
breakinside acaseexits thewhileloop, becausematchisn't a loop itself.
Step 4: Sample run
Here's a first session, starting with no saved file. Text after each prompt is what the user typed. Dates will show the day you run the program.
After adding two more expenses the same way (KES 3,500 for food with the note "groceries", and KES 1,500 for transport with the note "matatu fare"), the user views everything, asks for a summary and quits:
The percentages add up to 101% because each one is rounded separately. The start of budget.json now looks like this:
[
{
"date": "2026-03-14",
"kind": "income",
"amount": 25000.0,
"category": "salary",
"note": "March pay"
},
{
"date": "2026-03-14",
"kind": "expense",
"amount": 8000.0,
"category": "rent",
"note": ""
},
Run the program again and it greets you with "Loaded 4 saved transaction(s)."
Storing money as floats can create tiny rounding errors (for example, 0.1 + 0.2 is 0.30000000000000004). Rounding to two decimal places, as ask_amount() does, is fine for a personal tracker. Real banking software stores amounts as whole cents (integers) or uses the decimal module.
If you run the script from a different folder, it creates a new, empty budget.json there, and your old data seems to vanish. To always use the file next to the script, set DATA_FILE = Path(__file__).parent / "budget.json".
Extend it
- Monthly budgets: let the user set a limit for each category (for example KES 4,000 for food) and print a warning when spending goes over it.
- Filter by month: add a menu option that asks for a month such as
2026-03and shows only matching transactions (hint:t["date"].startswith("2026-03")). - Export and delete: export transactions to a CSV file you can open in Excel with
csv.DictWriter, and add an option to delete a transaction by its number. Later, try rewriting the program with aTransactionclass.
Key points
- A list of dictionaries is a simple, JSON-friendly way to store records.
- Validate input in a loop with
try/exceptso bad input never crashes the program. - Save after every change, and handle missing or damaged files gracefully.
- Format specifiers such as
:<12and:>11,.2fproduce neat columns.
Tip: use the ← and → keys to move between pages.
