Madras Academy
Home / Blog / Python / Build a Student Expense Tracker with Python and SQLite
Python

Build a Student Expense Tracker with Python and SQLite

Build a local expense tracker while learning Python functions, SQLite queries, input validation, reporting and practical software testing.

December 3, 2026 admin 7 min read

A student expense tracker is a useful first database project because it solves a familiar problem: remembering where money goes. Instead of building another calculator that forgets its results when it closes, you can create a small application that stores transactions, retrieves them later and produces meaningful summaries. This tutorial shows how to build a student expense tracker with Python and SQLite using only the Python standard library. The goal is not to create a banking application, but to understand how reliable software handles information from input to storage and reporting.

What will you learn from this project?

The project introduces database tables, primary keys, parameterised SQL statements, functions, validation and aggregation. You will also practise separating the responsibilities of a program: collecting information, checking whether it is acceptable, storing it and presenting results. These skills transfer to attendance systems, library catalogues, inventory applications and many other college projects.

Start with a command-line interface rather than a graphical dashboard. A terminal program makes it easier to understand the underlying logic before adding buttons, charts or web pages. Your first milestone is a working application that can record an expense and display totals after the program has been restarted.

Plan the features before writing code

Imagine a college student who spends money on transport, food, stationery and mobile data. Each expense needs a date, category, amount and optional note. The application should support adding records, viewing recent transactions and calculating spending by category for a selected month. Editing and deleting records can become later milestones.

Write down acceptance criteria for each feature. For example, entering a negative amount should not create a record, and a report for an empty month should display a friendly message. Defining these expectations early gives you a concrete way to judge whether the program works instead of relying on appearances alone.

Set up Python and SQLite

Install Python 3 and create a folder named expense_tracker. Inside it, create a file called tracker.py. Python includes the sqlite3 module, so this project does not require a separate database server or third-party package. SQLite stores the database in a local file. Run your program from the project folder so that you can easily locate the resulting database.

Students who are new to functions, loops and collections can first explore Madras Academy’s Python Programming for Absolute Beginners course. Familiarity with these fundamentals makes the database portion easier to follow.

Design a simple database table

Use an integer primary key to distinguish transactions, even when two expenses have identical dates and amounts. Store dates as ISO-format text such as 2026-12-03. Store amounts as integer paise rather than floating-point rupees to avoid rounding errors during addition. For example, โ‚น45.50 becomes 4550 paise. This is a straightforward design for a single-currency learning project.

import sqlite3
from contextlib import closing
from datetime import date
from decimal import Decimal, InvalidOperation

DB = "expenses.db"

def setup():
    with closing(sqlite3.connect(DB)) as conn:
        with conn:
            conn.execute("""
                CREATE TABLE IF NOT EXISTS expenses (
                    id INTEGER PRIMARY KEY,
                    spent_on TEXT NOT NULL,
                    category TEXT NOT NULL,
                    amount_paise INTEGER NOT NULL
                        CHECK(amount_paise > 0),
                    note TEXT NOT NULL DEFAULT ''
                )
            """)

The CREATE TABLE IF NOT EXISTS statement allows the setup function to run repeatedly without deleting earlier transactions. The CHECK constraint provides an additional safeguard against non-positive amounts. The connection context commits successful transactions and rolls back when an exception occurs; closing explicitly releases the connection afterwards.

Record an expense safely

Input validation is a major part of application development. A user may accidentally enter letters instead of a number, leave the category empty or type an impossible calendar date. Validate these values before sending them to the database. Decimal is useful for converting a text amount into paise without introducing binary floating-point rounding.

def add_expense(day, category, amount, note=""):
    day = date.fromisoformat(day).isoformat()
    category = category.strip().lower()
    if not category:
        raise ValueError("Category is required")
    try:
        value = Decimal(amount)
        if not value.is_finite() or not 0 < value <= 1000000:
            raise ValueError("Enter a positive amount up to 1000000")
        paise = value * 100
        if paise != paise.to_integral_value():
            raise ValueError("Use at most two decimal places")
    except InvalidOperation as exc:
        raise ValueError("Invalid amount") from exc
    with closing(sqlite3.connect(DB)) as conn:
        with conn:
            conn.execute(
                """INSERT INTO expenses
                (spent_on, category, amount_paise, note)
                VALUES (?, ?, ?, ?)""",
                (day, category, int(paise), note.strip())
            )

The question marks are SQL parameter placeholders. The database driver binds the supplied values separately from the SQL statement, so a note containing an apostrophe does not break the query. Avoid constructing SQL by concatenating user input. The example also normalises category names so that Food and food appear together in a report.

Generate a monthly spending report

SQL can perform calculations directly on stored records. GROUP BY collects transactions belonging to the same category, while SUM adds their amounts. Filtering by a month prevents older expenses from being included accidentally. Because dates are stored in a consistent format, a prefix filter is sufficient for this introductory project.

def monthly_report(month):
    if len(month) != 7:
        raise ValueError("Use YYYY-MM")
    date.fromisoformat(month + "-01")
    with closing(sqlite3.connect(DB)) as conn:
        rows = conn.execute("""
            SELECT category, SUM(amount_paise)
            FROM expenses
            WHERE spent_on LIKE ?
            GROUP BY category
            ORDER BY SUM(amount_paise) DESC
        """, (month + "%",)).fetchall()
    if not rows:
        print("No expenses for this month")
        return
    for category, paise in rows:
        print(f"{category}: Rs {paise // 100}.{paise % 100:02d}")

To test the functions, call setup(), add_expense(“2026-12-03”, “food”, “45.50”) and monthly_report(“2026-12”) at the bottom of the file. Run python tracker.py. You should see a food total of Rs 45.50 in a fresh database. Remove the sample insertion after testing, because running it again deliberately adds another transaction.

Turn the functions into a usable application

Once the database functions work, create a menu with options to add an expense, view a monthly report and exit. Use a while loop to keep the menu available until the user chooses to quit. Collect input with input(), call the appropriate function and catch ValueError to display a helpful message. Add a separate function that retrieves the latest ten transactions ordered by date and ID.

Keep the menu separate from database operations. This means that a future graphical interface or web application can reuse the same functions. If you later want to build an HTTP interface, Madras Academy’s Python Web Development with Flask & FastAPI course is a relevant next step.

Test your student project systematically

Create a separate test database or temporary project folder so that testing does not change real expense records. Check a valid expense, a zero amount, a negative amount, an invalid date, an empty category and an amount with three decimal places. Insert two food expenses and one transport expense, then compare the report against a calculation performed by hand. Close and reopen the program to verify persistence.

Record the expected result, actual result and pass or fail status for each case. This small testing document demonstrates that you understand software quality, not just coding syntax. You can later automate these checks using Python’s unittest module.

Real-world applications and future improvements

The same design can support a club’s event expenses, a small shop’s petty cash register or a household spending diary. These are examples of how the underlying technique transfers, not claims that the sample program is ready for commercial accounting. Real financial systems need stronger access controls, auditing, backups and carefully defined accounting rules.

For a second version, add CSV export, monthly budgets and category filters. Use fictional transactions in screenshots and public repositories. Do not commit a database containing personal financial information. Students interested in exporting reports and automating repetitive office tasks can explore Python Automation for Office & Business.

Frequently asked questions

Do I need to install MySQL?

No. Python’s sqlite3 module can create and access a local SQLite database without running a separate database server.

Can I complete this project as a beginner?

Yes, if you understand basic Python functions, strings and conditions. Build one feature at a time and test it before continuing.

Can multiple users share this application?

The example is intended for local, single-user practice. A shared application requires authentication, authorisation and additional design decisions around concurrent access and privacy.

How should I present it in my portfolio?

Include a README with setup instructions, a database schema, sample output, test results and a description of the limitations. Explain your choice of integer paise and parameterised queries during a project demonstration.

Take the next step with Madras Academy

Building a student expense tracker with Python and SQLite is an achievable way to connect programming fundamentals with database skills. Once the basic version works, improve it through small, measurable milestones. Contact Madras Academy to enquire about Python training, guided projects and suitable learning pathways for your current experience level.

RECOMMENDED COURSES

Continue learning with Madras Academy.

Here are a few courses selected from our current catalog.

Browse All Courses
W WhatsApp