Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Project

Stage 1 Project: Expense Tracker (CLI)

Start after Part 8

Stage 1

Goal: Build a real command-line app that records your daily spending, saves it to a JSON file, shows tables and summaries, and exports to CSV. Time: ~6–8 hours · Uses: Parts 2–8 only (no classes, no third-party packages)

Project brief

Every month you ask: "Where did my salary go?" Rent, groceries, petrol, food delivery, electricity bill... In this project you build a small tool that answers that question from the terminal. This demo works on test.json, a copy of the 7 sample expenses (see ▶️ How to run below), so the new expense gets id #8:

$ python expense_tracker.py --file test.json add 120 petrol --note "Bike top-up" --date 2026-11-20
Added expense #8: ₹120.00 on petrol (2026-11-20)

$ python expense_tracker.py --file test.json summary --month 2026-11
Summary for 2026-11
===================
Category            Amount   Share
----------------------------------
rent            ₹15,000.00   91.0%
...

Files

File What it is
README.md This brief and the step-by-step build guide
expense_tracker.py Complete reference solution (try building your own first!)
sample_expenses.json 7 sample expenses to test with
tests_manual.md Commands to try, with the exact expected output

How to run

Open a terminal in this folder (Python 3.13+). On macOS/Linux type python3 instead of python:

python expense_tracker.py --help                 # see all commands
python expense_tracker.py add 250 food --note "Dinner delivery"
python expense_tracker.py list

By default your data is saved in expenses.json next to the script. The file is created on the first add.

To test safely, work on a copy of the sample data with the global --file option. Note: --file goes before the command.

cp sample_expenses.json test.json                # Windows: copy sample_expenses.json test.json
python expense_tracker.py --file test.json list
python expense_tracker.py --file test.json summary --month 2026-10

Features

Command What it does Example
add <amount> <category> [--note TEXT] [--date YYYY-MM-DD] Add an expense. Date defaults to today. add 1200 petrol --note "Full tank" --date 2026-10-12
list [--month YYYY-MM] [--category C] Show expenses in a table with a total list --month 2026-11 --category rent
summary [--month YYYY-MM] Total, per-category totals with % share, biggest expense summary --month 2026-10
delete <id> Delete one expense by its id delete 3
export <file.csv> Save all expenses to a CSV file (opens in Excel) export november.csv

Error handling: bad input prints a clear Error: ... line and the program exits with code 1.

Bad input Message
add -50 food Error: Amount must be at least ₹0.01, got -50.
add abc food Error: Amount must be a number, got 'abc'.
add 100 food --date 2026-02-30 Error: Date must be a real date in YYYY-MM-DD format, got '2026-02-30'.
delete 99 Error: No expense with id 99.

Which Parts each feature uses

Feature Skills Part
Amounts, f-string table, ₹{amount:,.2f} numbers, strings, f-strings, type casting Part 2
Filters, loops, match on the command if/elif, for, continue, match-case Part 3
Expense as a dict, all expenses as a list dict, list, nesting Part 4
One job per function, sorted(key=lambda ...) def/return, default args, lambda Part 5
ExpenseError, try/except, exit code 1 raise, custom exceptions, except ... as e Part 6
import, if __name__ == "__main__", sys.exit, math modules, stdlib Part 7
JSON save/load, CSV export, dates, Path(__file__).parent files, with, pathlib, json, csv, datetime Part 8
add, list, --file options argparse (stdlib) New here (more in Stage 3, Part 16: Packaging)

💡 The only class in the solution is class ExpenseError(Exception), the custom exception from Part 6. Full OOP comes in Stage 2.

Small new tools you will meet

A real program needs a few small things the Parts did not show. Each one is one line to learn:

Tool What it does Example
isinstance(x, dict) True if x is a dict check the JSON file really holds a list
isinstance(x, (int, float)) True if x is any of the types in the tuple check an amount in the file is a number
sum(e["amount"] for e in expenses) add up one field from every item (like a list comprehension without []) total spending
max(..., default=0) max() of an empty list gives 0 instead of an error first id when there are no expenses
math.isfinite(x) False for nan and inf float("nan") works, but it is not a real amount
json.JSONDecodeError the error json.load() raises for broken JSON a hand-edited file with a typo
UnicodeDecodeError the error you get when a file is not UTF-8 text someone saved a picture as expenses.json
d.isoformat() a date as YYYY-MM-DD text date(2026, 1, 5).isoformat() → '2026-01-05'
path.replace(target) move a file over another one in one step atomic save (Step 2)
OSError parent of all file errors (FileNotFoundError, PermissionError ...) export to a folder that does not exist
print(..., file=sys.stderr) print to the error stream instead of normal output error messages
argparse reads the words typed after python expense_tracker.py add 250 food

Build it step by step

Build in small steps. Run your file after every step. Do not open expense_tracker.py until you have tried each step yourself.

Start your file with the constants (fixed settings) at the top, in UPPER_SNAKE_CASE. Then, if you want to change a format later, you change it in one place:

DATE_FORMAT = "%Y-%m-%d"
MONTH_FORMAT = "%Y-%m"
FIELDS = ["id", "date", "amount", "category", "note"]

Step 1: Decide the data format (Part 4)

What and why: before writing any logic, decide how one expense looks in memory. Every other function depends on this choice. One expense is a dict. All expenses are a list of dicts. This is exactly what JSON can store.

expense = {
    "id": 1,
    "date": "2026-10-01",      # string in YYYY-MM-DD, easy to sort and filter
    "amount": 15000.0,
    "category": "rent",
    "note": "October rent",
}
expenses = [expense]           # the whole "database"
print(len(expenses))           # 1
Field Type Why
id int so you can delete one expense
date str YYYY-MM-DD sorts correctly as text; "2026-11-03"[:7] == "2026-11" filters by month
amount float rupees and paise
category str (lowercase) Petrol and petrol become the same category
note str optional description

Open sample_expenses.json and look at the format.

🔍 Going deeper: why is amount a float? Floats are stored in binary, so 0.1 + 0.2 gives 0.30000000000000004 (Part 2). Here that is fine: we round every amount to paise with round(amount, 2) when we save it, and :,.2f rounds again when we print, so the tiny errors never show. It breaks when you add millions of amounts or need exact equality (total == 0.3 can be False). Banks avoid floats: they store paise as an int (₹99.50 → 9950) and divide by 100 only for display (Part 2: // and %). Python's decimal module is another exact option.

🔍 Going deeper: why JSON for saving and CSV only for export? JSON keeps types (15000.0 stays a number, id stays an int) and can grow nested data later. CSV turns everything into text, but every spreadsheet opens it. So: JSON is the app's own file, CSV is for sharing.

Step 2: Load and save JSON (Part 8)

What and why: your list lives only while the program runs. Saving it to a file lets you add an expense today and see it tomorrow. Write two functions. A missing file just means "no expenses yet", so return an empty list.

import json
from pathlib import Path

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

def load_expenses(path):
    if not path.exists():
        return []
    with open(path, encoding="utf-8") as f:
        return json.load(f)

def save_expenses(path, expenses):
    tmp_path = path.with_name(path.name + ".tmp")      # expenses.json.tmp
    with open(tmp_path, "w", encoding="utf-8") as f:
        json.dump(expenses, f, indent=2, ensure_ascii=False)
    tmp_path.replace(path)                             # swap in one step

✅ Test: expenses = load_expenses(Path("sample_expenses.json")) then print(len(expenses)) → 7.

Why the .tmp file? open(path, "w") empties the file first. If the program crashed in the middle of json.dump, your data would be lost. So we write everything to expenses.json.tmp and then replace() it over the old file. This is called an atomic save: the old file is swapped for the new one in one step, so you always have either the old data or the new data, never half a file.

🔍 Going deeper: replace() is atomic when both files are in the same folder (same disk), which is why the .tmp file sits right next to expenses.json. For full safety against a power cut, real databases also call os.fsync() to force the data onto the disk before the swap.

Step 3: Add an expense (Parts 2, 5, 8)

What and why: this is the main job of the app. Clean the user's text first, so the saved data is always neat.

  • New id = biggest id + 1: max((e["id"] for e in expenses), default=0) + 1.
  • Default date = today: date.today().strftime(DATE_FORMAT).
  • A date typed by the user: datetime.strptime(text, DATE_FORMAT) also accepts 2026-1-5. Save it as parsed.date().isoformat() → 2026-01-05, so every saved date has the same form (sorting and month filters need that).
  • Clean the category in one function and use it everywhere (add and filter): text.strip().lower(). Raise an error if it is empty.
  • Append the dict to the list, then save.

✅ Test: add one expense to a copy of the sample file and open the JSON. You should see id 8.

🔍 Going deeper: why not len(expenses) + 1? After deleting id 3 from 7 expenses, len + 1 gives 7 again, a duplicate. "Biggest + 1" never gives a duplicate. It can still reuse an id if you delete the newest expense. Databases avoid that by saving a separate "next id" counter.

Step 4: List with filters (Parts 3, 5)

What and why: you rarely want to see everything. Filters answer questions like "What did I spend in November?"

  • Loop over expenses. Use continue to skip ones that do not match month or category.
  • Month filter: e["date"][:7] != month (the first 7 characters are YYYY-MM). Clean the month first, so 2026-1 becomes 2026-01: datetime.strptime(text, MONTH_FORMAT).strftime(MONTH_FORMAT).
  • Sort by date: sorted(result, key=lambda e: (e["date"], e["id"])). The id breaks ties for two expenses on the same day.
  • Print a table with f-string alignment: < left, > right, a number for width.
expense = {"id": 6, "date": "2026-11-03", "amount": 456.0,
           "category": "food", "note": "Food delivery"}
money = f"₹{expense['amount']:,.2f}"
print(f"{expense['id']:>3}  {expense['date']:<10}  {expense['category']:<12}  "
      f"{money:>12}  {expense['note']}")
#   6 2026-11-03 food ₹456.00 Food delivery

✅ Test: list --month 2026-11 shows 3 rows and Total ₹16,355.00.

Step 5: Summary (Parts 4, 5)

What and why: a list shows every rupee; a summary shows the big picture: which category eats most of your salary.

  • Total: sum(e["amount"] for e in expenses).
  • Per category: build a dict with totals[cat] = totals.get(cat, 0) + amount.
  • Share %: amount / total * 100, formatted with :.1f.
  • Biggest expense: max(expenses, key=lambda e: e["amount"]).

✅ Test: summary --month 2026-10 shows rent 73.6% and total ₹20,390.50.

Step 6: Delete by id (Parts 3, 6)

What and why: everyone types a wrong amount sometimes. Delete lets you fix it (then add it again).

  • Loop with enumerate(). When the id matches, expenses.pop(index) and return it.
  • If the loop ends without a match, raise ExpenseError(f"No expense with id {expense_id}.").
  • Save after deleting.

✅ Test: delete 6 works once. Running it again gives Error: No expense with id 6.

Step 7: Export to CSV (Part 8)

What and why: your family or your CA wants a file they can open in Excel. CSV is that file. csv.DictWriter writes a list of dicts straight to a CSV file.

import csv

def export_csv(expenses, csv_path):
    with open(csv_path, "w", newline="", encoding="utf-8-sig") as f:
        writer = csv.DictWriter(f, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(expenses)

💡 newline="" stops blank lines between rows on Windows. Notes with a comma (Full tank, scooter) are quoted for you. encoding="utf-8-sig" adds an invisible mark (a BOM) at the start of the file. Excel needs it: without it, Excel shows ₹ and Hindi notes as junk like ₹. Google Sheets and Python read it fine either way.

✅ Test: open the CSV in Excel or Google Sheets.

Step 8: Command-line interface with argparse (new, uses Part 3 match)

What and why: so far you called functions from code. Now the user picks the action by typing a command. argparse reads the words after python expense_tracker.py, checks them, and builds --help for free. Each command (add, list ...) is a subparser with its own arguments.

import argparse
from pathlib import Path

DEFAULT_FILE = Path("expenses.json")   # the app uses Path(__file__).parent (Step 2)

parser = argparse.ArgumentParser(description="Track your daily expenses.")
parser.add_argument("--file", type=Path, default=DEFAULT_FILE)
sub = parser.add_subparsers(dest="command", required=True)

p_add = sub.add_parser("add", help="add a new expense")
p_add.add_argument("amount")
p_add.add_argument("category")
p_add.add_argument("--note", default="")
p_add.add_argument("--date")

args = parser.parse_args(["add", "250", "food"])   # in the app: parse_args()
print(args.command, args.amount, args.category)     # add 250 food

Then pick the action with match args.command: and one case per command (Part 3). Keep each case to one line that calls a small handle_add(args, expenses), handle_list(...) function.

✅ Test: python expense_tracker.py --help and python expense_tracker.py add --help.

🔍 Going deeper: subparsers give each command its own options and help page, like git commit and git push. dest="command" stores which one was typed. required=True makes argparse print a usage error (exit code 2) when no command is given. Options before the command (--file) belong to the main parser, so they go before add.

Step 9: Error handling (Part 6)

What and why: users type mistakes. A beginner app crashes with a long traceback; a good app prints one clear line and stops.

  1. Make one custom exception: class ExpenseError(Exception) with a docstring.
  2. Small validation functions raise it with a clear message:
    • amount: float(text) inside try, ValueError → "must be a number". Then round first to paise, then check <= 0 → "must be at least ₹0.01" (so 0.001, which rounds to 0.0, is refused).
    • date: datetime.strptime(text, DATE_FORMAT) raises ValueError for 2026-02-30.
    • month: datetime.strptime(text, MONTH_FORMAT).
    • broken JSON file: catch json.JSONDecodeError (and UnicodeDecodeError for a file that is not text).
    • each record in the file: right fields and right types (id an int, amount a number, date a real YYYY-MM-DD, category and note strings). Watch out: True counts as an int in Python, so check isinstance(x, bool) too.
  3. main() catches it in one place, prints to sys.stderr, and returns 1:
import sys

# ... constants, ExpenseError, build_parser() and run() go above main() ...

def main():
    args = build_parser().parse_args()
    try:
        run(args)
    except ExpenseError as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1
    except OSError as e:                # no permission, folder missing...
        print(f"Error: could not read or write a file ({e.strerror})",
              file=sys.stderr)
        return 1
    return 0

if __name__ == "__main__":
    sys.exit(main())

✅ Test: run all the error cases in tests_manual.md. Each should print Error: ... and exit with code 1.

🔍 Going deeper: the exit code tells other programs (scripts, CI) whether you succeeded: 0 = OK, 1 = your error, 2 = argparse usage error. Errors go to stderr, so python expense_tracker.py list > out.txt saves the table but still shows errors on screen. Only ExpenseError and OSError are caught: a real bug should still crash loudly so you can fix it.


Stretch goals

  • 🟢 list --sort amount to sort by amount instead of date.
  • 🟢 categories command: print all categories you have used.
  • 🟡 edit <id> [--amount] [--category] [--note] [--date] to change an expense.
  • 🟡 Monthly budget: budget food 3000 saves a limit; summary warns when you cross it.
  • 🟡 import <file.csv>: read expenses back from CSV (watch out: CSV gives you strings, convert amount to float).
  • 🟡 Keep a backup: before each save, copy the old file to expenses.json.bak.
  • 🔴 Indian number format: ₹1,50,000.00 instead of ₹150,000.00 (write your own formatting function).
  • 🔴 report --year 2026: one line per month with a simple text bar chart (████).

Checklist

  • I can store records as a list of dicts and save/load them as JSON.
  • I can filter and sort data with loops and sorted(key=...).
  • I can group totals by category with a dict.
  • I can print a neat table with f-string alignment.
  • I can validate dates with datetime.strptime.
  • I can raise a custom exception and catch it in one place in main().
  • I can export data to CSV with csv.DictWriter.
  • I can build a CLI with argparse subcommands and a global --file option.
  • All commands in tests_manual.md give the expected output.

Next

🎉 Stage 1 done! Go back to the roadmap and start Stage 2: Part 9, Object-oriented Python. Good idea: rebuild this tracker with an Expense class there.

Search the guide