Capstone: Final Mini Project
Build a complete command-line expense tracker by turning requirements into functions, validating input, saving JSON data, and testing the result.
In this lesson, you will learn
- ✓Convert a practical problem into clear, testable requirements.
- ✓Design a small Python program using focused functions and appropriate data structures.
- ✓Validate user input and handle expected errors safely.
- ✓Save and load structured data using JSON files.
- ✓Test normal cases, invalid input, and important edge cases.
- ✓Explain the program's limitations, complexity, and possible improvements.
1. Define the problem before writing code
Imagine that you want a simple program to record everyday expenses. Writing code immediately can lead to missing features, unclear functions, and difficult-to-fix errors. Start by describing what the program must do.
A requirement describes observable behavior. For example, 'the program must reject an expense of zero' is testable: enter zero and check whether the program refuses to save it.
Keep the first version deliberately small. This project stores a description, category, amount, and date for each expense. It supports adding expenses, listing them, viewing a total, and exiting the program.
The project uses a JSON file named expenses.json in the current working directory. This makes records available after the program exits, provided the file can be read and written successfully.
Project requirements
Each requirement describes behavior rather than an implementation detail. The requirements can be turned into individual tests. The first version intentionally excludes features such as editing records, recurring payments, budgets, and multiple currencies.
Note
2. Design the data and functions
Choose a representation before building the menu. Each expense will be a dictionary with four keys: description, category, amount, and date. All expenses will be stored in a list of these dictionaries.
A dictionary is suitable because each field has a descriptive name. A list is suitable because the program needs to store multiple expenses and visit them in order.
For example, one record might contain a description of 'Lunch', a category of 'Food', an amount of 120.0, and a date such as '2026-10-13'. The date shown here is illustrative; the program generates the actual date when an expense is added.
Divide the work into functions. Loading and saving data should not be mixed into every menu branch. Separate functions make the code easier to understand and test.
Represent one expense
A dictionary associates each field name with a value. The amount is stored as a number, not as formatted currency text. The date is stored as an ISO-formatted string, which is convenient for display and JSON serialization.
Note
3. Build the expense tracker
The following program is a complete first version. Save it as expense_tracker.py and run it with Python 3. The expenses.json file will be created in the current working directory when the program first saves records.
The program loads existing records when it starts. It validates descriptions, categories, and amounts before accepting a new expense. It then saves the updated list to JSON.
The JSON loader handles a missing file by starting with an empty list. It does not silently replace a malformed JSON file with empty data: a corrupted file produces a clear error instead, helping prevent accidental data loss.
This is a local learning project, not a financial system. It does not provide encryption, backups, concurrent-write protection, or financial-grade decimal arithmetic.
Complete runnable project
The imports provide JSON serialization, numeric validation, and the current date. Path identifies the local data file. The with statement closes the file automatically, including when an error occurs. load_expenses handles a missing file separately from malformed JSON and checks the basic structure of stored records. read_positive_amount keeps asking until it receives a valid finite positive number. add_expense appends the new record and saves it. If writing fails, it removes the unsaved record from memory. list_expenses handles an empty list and uses enumerate to number the displayed records. show_total uses sum with a generator expression to add every recorded amount. main uses a while loop to keep the menu running until the user selects Exit. The if __name__ == '__main__' guard means main runs when this file is executed directly, but not simply when it is imported as a module.
Caution
4. Trace the program with a sample session
A dry run means following the program step by step without guessing what it will do. Start with an empty data file, choose Add expense, enter valid values, and then request the total.
The exact date depends on the machine's local date. The session below uses 2026-10-13 only as an illustration. The numeric total and menu behavior are deterministic for the shown inputs.
Illustrative terminal session
The first choice enters the branch for adding an expense. The program strips surrounding whitespace from the description and category, then validates the amount. The record is appended to the list and written to the JSON file. The total is calculated from the in-memory list. Because the saved record has an amount of 120.0, the formatted total is 120.00. The loop ends only after the user chooses 4.
Note
5. Understand JSON persistence and error handling
A Python list exists in memory while the process is running. When the program exits, that in-memory list disappears. Saving it to a file lets the next run restore the records.
JSON represents common data structures using text. Python's json.dump writes a Python value to an open file, while json.load reads JSON from an open file and converts it back into Python values.
The with statement manages the file's lifetime. It closes the file when the block ends, even if an exception is raised.
A missing file is normal on the first run, so the loader returns an empty list for FileNotFoundError. Invalid JSON is different: the program reports a problem instead of silently treating corrupted data as a new empty tracker.
Saving is not guaranteed to succeed. Permissions, a full disk, or an unavailable path can cause an OSError. The program catches that error when adding an expense and does not claim the record was saved.
How the saved JSON looks
The square brackets represent a list. Each object contains four fields. The date and descriptive fields are strings; the amount is a JSON number. The date in this example is illustrative. The program uses date.today() when creating a real record.
Caution
6. Test behavior, not just whether the program starts
A program can start successfully and still be wrong. Testing means checking that particular inputs produce the expected behavior.
Test the normal path first: adding a valid expense should increase the number of records and update the total. Then test boundaries and invalid input, such as an empty description, a non-numeric amount, zero, a negative amount, or an invalid menu choice.
The helper functions that receive ordinary values are easier to test than functions that call input directly. For example, is_valid_amount can be tested with a range of numbers without typing anything.
The small test below uses Python's standard unittest framework. It tests amount validation independently of the interactive menu.
Unit tests for amount validation
The displayed test summary is representative of a successful run; it is not a captured execution result from this lesson authoring session. Each test checks one specific behavior. The tests cover a normal positive amount and several invalid numeric values. Run the test file with Python to confirm the actual result in your environment.
Note
7. Complexity and limitations
Let n be the number of saved expenses. Adding an expense appends to a Python list in amortized O(1) time, but saving the complete list to JSON takes O(n) time. Listing all records and calculating the total also take O(n) time.
The program keeps all expenses in memory and writes the complete list whenever a record is added. This is reasonable for a small learning project, but it becomes inefficient for very large datasets.
The program's space usage is O(n) because it retains all records in memory and serializes the full collection when saving.
The project also has clear limitations: amounts use floating-point numbers, records cannot be edited or deleted, the data file is local to the current working directory, and simultaneous instances can overwrite one another's changes.
Complexity summary
Appending a record to a list is amortized constant time, but the complete add-and-save operation is linear because the whole file is rewritten. Listing visits every record. Calculating the total visits each amount once. The space required grows with the number of stored records.
Note
8. Review and improve the project
Before calling the project complete, compare the implementation with the original requirements. Confirm that valid expenses are saved, invalid amounts are rejected, existing data is loaded, totals are correct, and the program exits when requested.
Read each function and ask whether its responsibility is clear. Avoid copying the same logic into multiple places. For example, the amount-validation logic belongs in a helper that can be tested independently.
A useful review also considers failure behavior. What happens when expenses.json does not exist? What happens if the JSON is malformed? What happens when a user enters a menu choice that is not supported? The program should have deliberate behavior for these situations.
Only add extra features after the first version works. Possible extensions include category totals, deleting an expense, date-range reports, exporting CSV, and automated tests for file persistence.
Final acceptance checklist
The checklist maps directly to observable requirements. Passing the checklist is more meaningful than judging the project by its line count. For a stronger submission, include a README explaining setup, execution, supported features, limitations, and how to run the tests.
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Starting to code without deciding what the program should do.
Why it happens: A clear specification defines required operations, data fields, validation rules, and persistence behavior before implementation begins.
Key takeaway: Write a short requirement list and turn each requirement into an observable check.
#2 Storing every expense as one formatted string.
Why it happens: Keeping expenses as structured records with separate amount, category, date, and description fields makes validation and summaries reliable.
Key takeaway: Use dictionaries with separate fields so calculations and filtering remain straightforward.
#3 Assuming input() always returns a valid number.
Why it happens: input() always returns text; convert numeric input and handle conversion failures before using it in calculations.
Key takeaway: Convert the text inside a try/except block and reject values that do not meet the requirement.
#4 Checking only whether an amount is greater than zero.
Why it happens: A positive amount check alone may be insufficient; validate type, finite value, allowed range, and any domain-specific currency rules.
Key takeaway: Also reject non-finite floating-point values such as NaN and infinity.
#5 Treating every file-loading error as an empty expense list.
Why it happens: A malformed or unreadable data file is not necessarily an empty dataset; distinguish a missing first-run file from corruption or permission errors.
Key takeaway: Handle a missing file separately from malformed JSON and other file errors.
#6 Reporting that a record was saved before the file write succeeds.
Why it happens: Only report a successful save after the write completes; handle filesystem failures so users do not believe unsaved data is persisted.
Key takeaway: Print success only after saving completes without an error.
#7 Assuming that a program is correct because it runs once.
Why it happens: One successful run cannot test all features or error paths; verify representative inputs, boundaries, and repeat runs.
Key takeaway: Test normal behavior, invalid input, empty collections, persistence, and failure cases.
#8 Using floating-point numbers without recognizing their limitations for money.
Why it happens: Binary floating-point can represent some decimal currency amounts approximately; use integer minor units or Decimal when exact financial arithmetic is required.
Key takeaway: Use Decimal or integer minor units in a more serious financial application.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:How do you approach building a small project from scratch?
Q2:Why does the expense tracker use a list of dictionaries?
Q3:What is the difference between json.dump and json.load?
Q4:Why is exception handling important in a command-line program?
Q5:Why validate a numeric value after converting it to float?
Q6:What is a unit test?
Q7:What is the time complexity of calculating the expense total?
Q8:Why is float not ideal for financial calculations?
Q9:What does the __name__ == '__main__' guard do?
Q10:How would you improve this project for real-world use?
Key takeaways
- Start with requirements that can be checked.
- Choose data structures that match the problem.
- Use focused functions to separate responsibilities.
- Validate external input before using it.
- Use JSON to persist suitable Python data structures.
- Handle expected errors without claiming an operation succeeded when it failed.
- Test normal inputs, boundaries, and invalid values.
- Review limitations and document how to run the project.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: