Skip to content
PythonAlgorithms and Capstone Practicebeginner45 min read

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

Project requirements
text
1. Add an expense with a description, category, and positive amount.
2. Reject blank descriptions and categories.
3. Reject amounts that are invalid, zero, negative, NaN, or infinite.
4. List saved expenses with their dates and amounts.
5. Calculate the total of all saved expenses.
6. Save changes to expenses.json.
7. Handle a missing data file and invalid menu choices.
8. Exit without losing successfully saved records.
Output
Eight observable 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

Planning does not mean creating a complicated document. A short list of clear requirements is enough for a project of this size.

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

Represent one expense
python
expense = {
'description': 'Lunch',
'category': 'Food',
'amount': 120.0,
'date': '2026-10-13'
}
 
print(expense['description'])
print(expense['amount'])
Output
Lunch 120.0

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

This is a small procedural design. A beginner does not need classes or a complex package structure to build a useful first version.

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

Complete runnable project
python
import json
import math
from datetime import date
from pathlib import Path
 
DATA_FILE = Path('expenses.json')
 
 
def load_expenses():
"""Load expense records, or return an empty list if no file exists."""
try:
with DATA_FILE.open('r', encoding='utf-8') as file:
expenses = json.load(file)
except FileNotFoundError:
return []
except json.JSONDecodeError as error:
raise ValueError('The expense file contains invalid JSON.') from error
 
if not isinstance(expenses, list):
raise ValueError('The expense file must contain a JSON list.')
 
required_keys = {'description', 'category', 'amount', 'date'}
for expense in expenses:
if not isinstance(expense, dict) or not required_keys.issubset(expense):
raise ValueError('The expense file contains an invalid record.')
if not isinstance(expense['description'], str):
raise ValueError('An expense description is invalid.')
if not isinstance(expense['category'], str):
raise ValueError('An expense category is invalid.')
if not isinstance(expense['amount'], (int, float)) or isinstance(expense['amount'], bool):
raise ValueError('An expense amount is invalid.')
if not math.isfinite(expense['amount']) or expense['amount'] <= 0:
raise ValueError('An expense amount must be finite and positive.')
if not isinstance(expense['date'], str):
raise ValueError('An expense date is invalid.')
 
return expenses
 
 
def save_expenses(expenses):
"""Write all expense records to the JSON data file."""
with DATA_FILE.open('w', encoding='utf-8') as file:
json.dump(expenses, file, indent=4, allow_nan=False)
 
 
def read_positive_amount():
"""Ask until the user enters a finite number greater than zero."""
while True:
raw_amount = input('Amount: ').strip()
try:
amount = float(raw_amount)
except ValueError:
print('Enter a valid number, such as 125 or 49.50.')
continue
 
if not math.isfinite(amount) or amount <= 0:
print('Amount must be a finite number greater than zero.')
continue
 
return amount
 
 
def add_expense(expenses):
"""Collect a valid expense, append it, and save the records."""
description = input('Description: ').strip()
if not description:
print('Description cannot be blank.')
return
 
category = input('Category: ').strip()
if not category:
print('Category cannot be blank.')
return
 
amount = read_positive_amount()
expense = {
'description': description,
'category': category,
'amount': amount,
'date': date.today().isoformat()
}
 
expenses.append(expense)
try:
save_expenses(expenses)
except OSError as error:
expenses.pop()
print(f'Could not save the expense: {error}')
return
 
print('Expense saved successfully.')
 
 
def list_expenses(expenses):
"""Display all records, or explain that no records exist."""
if not expenses:
print('No expenses recorded yet.')
return
 
print('\nSaved expenses')
print('-' * 50)
for index, expense in enumerate(expenses, start=1):
print(
f"{index}. {expense['date']} | {expense['category']} | "
f"{expense['description']} | {expense['amount']:.2f}"
)
 
 
def show_total(expenses):
"""Calculate and display the sum of all recorded expenses."""
total = sum(expense['amount'] for expense in expenses)
print(f'Total expenses: {total:.2f}')
 
 
def main():
try:
expenses = load_expenses()
except (OSError, ValueError) as error:
print(f'Could not load expense data: {error}')
return
 
while True:
print('\nExpense Tracker')
print('1. Add expense')
print('2. List expenses')
print('3. Show total')
print('4. Exit')
choice = input('Choose an option: ').strip()
 
if choice == '1':
add_expense(expenses)
elif choice == '2':
list_expenses(expenses)
elif choice == '3':
show_total(expenses)
elif choice == '4':
print('Goodbye!')
break
else:
print('Invalid choice. Enter 1, 2, 3, or 4.')
 
 
if __name__ == '__main__':
main()
Output
The program displays the menu and waits for a choice. After valid input, it adds, lists, or totals expenses; choosing 4 prints Goodbye! and exits.

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

The program uses float for amounts to keep this beginner project accessible. Floating-point arithmetic can produce rounding differences, so real financial applications should use Decimal or integer minor units, such as paise. The file-writing approach also assumes one program instance at a time.

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

Illustrative terminal session
text
Expense Tracker
1. Add expense
2. List expenses
3. Show total
4. Exit
Choose an option: 1
Description: Lunch
Category: Food
Amount: 120
Expense saved successfully.
 
Expense Tracker
1. Add expense
2. List expenses
3. Show total
4. Exit
Choose an option: 3
Total expenses: 120.00
 
Expense Tracker
1. Add expense
2. List expenses
3. Show total
4. Exit
Choose an option: 4
Goodbye!
Output
One expense is saved, the total is displayed as 120.00, and the program exits.

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

The session is a worked example, not a claim that the program was executed in this environment.

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

How the saved JSON looks
json
[
{
"description": "Lunch",
"category": "Food",
"amount": 120.0,
"date": "2026-10-13"
}
]
Output
A JSON array containing one expense object

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

The example does not implement backups or atomic file replacement. For an application holding important records, design a recovery strategy before adding more features.

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

Unit tests for amount validation
python
import math
import unittest
 
 
def is_valid_amount(amount):
return math.isfinite(amount) and amount > 0
 
 
class AmountValidationTests(unittest.TestCase):
def test_positive_amount_is_valid(self):
self.assertTrue(is_valid_amount(12.5))
 
def test_zero_is_invalid(self):
self.assertFalse(is_valid_amount(0))
 
def test_negative_amount_is_invalid(self):
self.assertFalse(is_valid_amount(-1))
 
def test_nan_is_invalid(self):
self.assertFalse(is_valid_amount(float('nan')))
 
def test_infinity_is_invalid(self):
self.assertFalse(is_valid_amount(float('inf')))
 
 
if __name__ == '__main__':
unittest.main()
Output
Ran 5 tests OK

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

These tests cover the amount-validation helper, not every behavior of the complete application. A stronger next step is to test JSON loading and saving with temporary files and test interactive functions with mocked input.

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

Complexity summary
text
Add to in-memory list: amortized O(1)
Save all records: O(n)
List all records: O(n)
Calculate total: O(n)
Store records in memory: O(n)
Output
Most operations that visit or save every record grow linearly with n.

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

Complexity describes how work grows with input size. It does not directly measure the exact number of seconds on a particular computer.

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

Final acceptance checklist
text
[ ] A first run works when expenses.json does not exist.
[ ] A valid expense can be added and saved.
[ ] Saved records appear after restarting the program.
[ ] Blank descriptions and categories are rejected.
[ ] Invalid, zero, negative, NaN, and infinite amounts are rejected.
[ ] Listing an empty tracker displays a helpful message.
[ ] The total matches the saved records.
[ ] Invalid menu choices do not crash the program.
[ ] File errors are reported clearly.
[ ] Unit tests cover normal and invalid amount values.
Output
Ten project-review checks

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.

Incorrect Approach
script.py
python
Starting to code without deciding what the program should do.
Correct Solution
script.py
python
Write a short requirement list and turn each requirement into an observable check.

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.

Incorrect Approach
script.py
python
Storing every expense as one formatted string.
Correct Solution
script.py
python
Use dictionaries with separate fields so calculations and filtering remain straightforward.

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.

Incorrect Approach
script.py
python
Assuming input() always returns a valid number.
Correct Solution
script.py
python
Convert the text inside a try/except block and reject values that do not meet the requirement.

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.

Incorrect Approach
script.py
python
Checking only whether an amount is greater than zero.
Correct Solution
script.py
python
Also reject non-finite floating-point values such as NaN and infinity.

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.

Incorrect Approach
script.py
python
Treating every file-loading error as an empty expense list.
Correct Solution
script.py
python
Handle a missing file separately from malformed JSON and other file 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.

Incorrect Approach
script.py
python
Reporting that a record was saved before the file write succeeds.
Correct Solution
script.py
python
Print success only after saving completes without an error.

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.

Incorrect Approach
script.py
python
Assuming that a program is correct because it runs once.
Correct Solution
script.py
python
Test normal behavior, invalid input, empty collections, persistence, and failure cases.

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.

Incorrect Approach
script.py
python
Using floating-point numbers without recognizing their limitations for money.
Correct Solution
script.py
python
Use Decimal or integer minor units in a more serious financial application.

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.

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?
Answer:
I first define requirements and acceptance criteria, then choose suitable data structures and split the work into focused functions. I implement the core behavior, validate inputs, handle expected errors, test normal and edge cases, and review the limitations before documenting how to run the program.
Q2:Why does the expense tracker use a list of dictionaries?
Answer:
A list holds multiple records in order, while each dictionary maps descriptive field names to their values. This representation is easy to iterate over, calculate totals from, and serialize as JSON.
Q3:What is the difference between json.dump and json.load?
Answer:
json.dump serializes a Python object to an open file as JSON. json.load reads JSON from an open file and converts it into Python objects.
Q4:Why is exception handling important in a command-line program?
Answer:
Users can enter invalid values, and files can be missing, malformed, or inaccessible. Handling expected exceptions lets the program report the problem clearly rather than terminating unexpectedly or pretending an operation succeeded.
Q5:Why validate a numeric value after converting it to float?
Answer:
Successful conversion does not guarantee that a value is suitable. The program must still check the application's constraints, including whether the value is finite and greater than zero.
Q6:What is a unit test?
Answer:
A unit test checks a small, focused piece of behavior in isolation. For example, tests for amount validation check positive values and invalid boundaries without needing to interact with the menu.
Q7:What is the time complexity of calculating the expense total?
Answer:
It is O(n), where n is the number of records, because each expense amount is visited once. The program's complete add-and-save operation is also O(n) because it rewrites the full JSON list.
Q8:Why is float not ideal for financial calculations?
Answer:
Binary floating-point cannot represent every decimal fraction exactly, which can cause small rounding errors. A more serious financial application should consider Decimal or integer minor units such as paise.
Q9:What does the __name__ == '__main__' guard do?
Answer:
It calls main when the file is executed directly. If the module is imported, its functions can be reused without automatically starting the interactive menu.
Q10:How would you improve this project for real-world use?
Answer:
I would add stronger automated tests, safer file replacement and backups, precise money representation, editing and deletion, category and date reports, and clear documentation. If multiple users or simultaneous writes were needed, I would consider a database and appropriate access controls.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: