Programming fundamentals · Beginner · 22 min
Handle bad input and finish the budget tracker
By Padding · Updated 18 Nov 2026
Python 3.15.2 · pytest 9.2.0 · python:3.15-slim
You will make the Python budget tracker survive bad typing with try and except, give blank categories a default, add a monthly report, test it with pytest and finish with a documented program of about 160 lines.
On this page
Your budget tracker works, as long as everyone types exactly what it expects. Type abc or 1,500 at the Amount prompt and it stops with a traceback, and every expense you typed in that session is lost. Type -200 and it records a negative expense without a word. Programs used by real people meet bad input all the time: a thumb slips on a phone keyboard, someone writes a number the way their country writes numbers, someone presses Enter too early.
In this final part you make the tracker survive all of that. It asks again instead of crashing, fills in a category when you leave it blank, saves each expense the moment you enter it, and gains a monthly report that shows what share of your budget each category took. Then you write three automatic tests with pytest and a README, so the program is finished in the way working programmers mean it: it runs, it is checked and someone else could pick it up.
This is part 8 of 8 in the series Learn to program from zero. Amounts are whole units of your own currency. The examples use a monthly budget of 50000.
Step 1 · Start from the part 7 tracker and break it
Go to the tracker folder you have used for the whole series, ~/budget-tracker (the command creates it if you are starting here):
mkdir -p ~/budget-tracker
cd ~/budget-trackerIf you finished part 7, this folder already holds an expenses.csv with the expenses you typed then. Every output in this part assumes the tracker starts with no saved expenses, so move your old file aside under a new name. Nothing is deleted: expenses-part7.csv keeps all your rows, and you can open it in a spreadsheet or rename it back later. If there is no expenses.csv yet, the command does nothing:
if [ -f expenses.csv ]; then mv expenses.csv expenses-part7.csv; fi
ls[ -f expenses.csv ] is true only when that file exists, so mv (move, which also renames) runs only then.
Next, make sure budget.py is the tracker exactly as part 7 left it. If you finished part 7 and kept your file as it was, it already matches and you can skip writing it again. If you are starting here, or you changed your copy, write this version so your screen matches every output below:
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 7)
import csv
from pathlib import Path
currency = "NGN"
EXPENSES_FILE = Path("expenses.csv")
FIELDS = ["item", "category", "amount"]
def ask_for_expense():
"""Ask for one expense. Return it as a dictionary, or None after done."""
item = input("Item (or done): ")
if item.strip().lower() == "done":
return None
category = input("Category: ").lower()
amount = int(input("Amount: "))
return {"item": item, "category": category, "amount": amount}
def total_spent(expenses):
"""Return the sum of all the amounts."""
spent = 0
for expense in expenses:
spent += expense["amount"]
return spent
def total_by_category(expenses):
"""Return a dictionary of category name to amount spent."""
totals = {}
for expense in expenses:
category = expense["category"]
if category in totals:
totals[category] = totals[category] + expense["amount"]
else:
totals[category] = expense["amount"]
return totals
def print_summary(expenses):
"""Print the table, the biggest expense and the totals per category."""
print()
print("Spending summary")
print("-" * 32)
for expense in expenses:
print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
print("-" * 32)
print(f"{len(expenses)} expenses, spent {total_spent(expenses):,}")
if len(expenses) > 0:
biggest = expenses[0]
for expense in expenses:
if expense["amount"] > biggest["amount"]:
biggest = expense
print(f"Biggest: {biggest['item']} ({biggest['amount']:,})")
totals = total_by_category(expenses)
print()
print("By category")
for category, total in totals.items():
print(f"{category:<24}{total:>8,}")
def save_expenses(expenses):
"""Write every expense to EXPENSES_FILE, replacing what was there."""
with open(EXPENSES_FILE, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=FIELDS)
writer.writeheader()
writer.writerows(expenses)
def load_expenses():
"""Return the saved expenses, or an empty list if there is no file yet."""
if not EXPENSES_FILE.exists():
return []
expenses = []
with open(EXPENSES_FILE, newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
row["amount"] = int(row["amount"])
expenses.append(row)
return expenses
def main():
expenses = load_expenses()
if expenses:
print(f"Loaded from {EXPENSES_FILE}: {len(expenses)} expense(s).")
else:
print("No saved expenses yet. Starting a new list.")
budget = int(input("Monthly budget: "))
while True:
expense = ask_for_expense()
if expense is None:
break
expenses.append(expense)
save_expenses(expenses)
print(f"Saved to {EXPENSES_FILE}: {len(expenses)} expense(s).")
print_summary(expenses)
left = budget - total_spent(expenses)
print()
if left < 0:
print(f"Warning: over budget by {currency} {-left:,}")
elif left < budget / 10:
print(f"Careful: only {currency} {left:,} left")
else:
print(f"You have {currency} {left:,} left this month.")
if __name__ == "__main__":
main()
PYRun it once and add one expense, so there is something saved:
printf '50000\nRice\nfood\n4000\ndone\n' | python3 budget.pyAs in earlier parts, printf types the answers for you: each \n is a press of Enter. Run python3 budget.py on its own to type them yourself. If you installed Python with uv, use uv run budget.py here and in every later step.
Now give it something it does not expect. This run types abc as the amount:
printf '50000\nBus fare\ntransport\nabc\n' | python3 budget.py || echo "exit status $?"The || echo "exit status $?" part prints the program's exit status when it fails. An exit status of 0 means success; anything else means something went wrong.
Check it worked
The ls before writing the program lists budget.py and, if you came from part 7, expenses-part7.csv but no expenses.csv. The first run prints No saved expenses yet. Starting a new list. and Saved to expenses.csv: 1 expense(s)., then a summary table with Rice in it and, on the last line, You have NGN 46,000 left this month. The second run ends with a traceback like this:
File "/home/you/budget-tracker/budget.py", line 16, in ask_for_expense
amount = int(input("Amount: "))
ValueError: invalid literal for int() with base 10: 'abc'
exit status 1Your path will show your own home folder, there are a few more File lines above these, and your traceback may also show ^ markers under the failing call. Read the traceback from the bottom up: the last line names the error, ValueError, and the lines above show where it happened. int() cannot turn abc into a number, so it raises a ValueError, and because nothing in the program deals with it, Python stops. Run cat expenses.csv: the bus fare is not there. The crash happened before save_expenses() ran.
Step 2 · Catch the error with try and except
An error like ValueError is called an exception. Python raises it when something cannot be done, and by default an exception stops the program. You can tell Python "try this, and if this particular exception happens, do something else instead of stopping". Create a practice file next to budget.py:
cat > tryit.py <<'PY'
answer = input("Amount: ")
try:
amount = int(answer)
print(f"Got the number {amount}.")
except ValueError:
print(f"Sorry, '{answer}' is not a whole number.")
print("The program is still running.")
PYLine by line:
answer = input("Amount: ")reads whatever was typed, as text.try:starts a block of code that Python will watch for exceptions. The two indented lines under it are that block.amount = int(answer)is the line that might fail. If it works, Python carries on to theprintbelow it.except ValueError:says what to do if aValueErrorhappens anywhere in thetryblock. Python jumps straight here and skips the rest of thetryblock.- The
printunderexceptruns only when the conversion failed. - The last
printis not indented, so it runs either way. The program keeps going.
Run it with six different answers. The for loop here is a shell loop that runs the program once per answer:
for answer in 1500 abc ' 250 ' 1,500 12.5 -300; do
printf '%s\n' "$answer" | python3 tryit.py
doneName the exception you expect, as except ValueError: does. A bare except: with no name would also catch exceptions you did not plan for, including a typing mistake in your own code and the KeyboardInterrupt that Ctrl+C raises, and hide them behind the friendly message.
Check it worked
You see twelve lines, two per run:
Amount: Got the number 1500.
The program is still running.
Amount: Sorry, 'abc' is not a whole number.
The program is still running.
Amount: Got the number 250.
The program is still running.
Amount: Sorry, '1,500' is not a whole number.
The program is still running.
Amount: Sorry, '12.5' is not a whole number.
The program is still running.
Amount: Got the number -300.
The program is still running.Three things to notice. int() ignores spaces around the number, so ' 250 ' works. It rejects 1,500 and 12.5, which is what you want: in many countries, including much of francophone Africa, a comma marks decimals, so guessing what 1,500 means could record the wrong amount. And -300 is a perfectly good whole number to Python, so try and except alone will not stop negative expenses. The next step handles that. Delete the practice file when you are done:
rm tryit.pyStep 3 · Ask again for bad amounts and fill in a blank category
Catching the error is half the job. The tracker should then ask again, and keep asking until the answer makes sense. That is a while loop, like the one from part 4, with try and except inside it. Replace budget.py with this version:
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 8)
import csv
from pathlib import Path
currency = "NGN"
EXPENSES_FILE = Path("expenses.csv")
FIELDS = ["item", "category", "amount"]
DEFAULT_CATEGORY = "other"
def ask_for_amount(prompt):
"""Ask until the answer is a whole number above 0, then return it."""
while True:
answer = input(prompt).strip()
try:
amount = int(answer)
except ValueError:
print(f"'{answer}' is not a whole number. Type digits only, like 1500.")
continue
if amount <= 0:
print("The amount must be more than 0.")
continue
return amount
def ask_for_expense():
"""Ask for one expense. Return it as a dictionary, or None after done."""
item = input("Item (or done): ")
if item.strip().lower() == "done":
return None
category = input(f"Category [{DEFAULT_CATEGORY}]: ").strip().lower()
if category == "":
category = DEFAULT_CATEGORY
amount = ask_for_amount("Amount: ")
return {"item": item, "category": category, "amount": amount}
def total_spent(expenses):
"""Return the sum of all the amounts."""
spent = 0
for expense in expenses:
spent += expense["amount"]
return spent
def total_by_category(expenses):
"""Return a dictionary of category name to amount spent."""
totals = {}
for expense in expenses:
category = expense["category"]
if category in totals:
totals[category] = totals[category] + expense["amount"]
else:
totals[category] = expense["amount"]
return totals
def print_summary(expenses):
"""Print the table, the biggest expense and the totals per category."""
print()
print("Spending summary")
print("-" * 32)
for expense in expenses:
print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
print("-" * 32)
print(f"{len(expenses)} expenses, spent {total_spent(expenses):,}")
if len(expenses) > 0:
biggest = expenses[0]
for expense in expenses:
if expense["amount"] > biggest["amount"]:
biggest = expense
print(f"Biggest: {biggest['item']} ({biggest['amount']:,})")
totals = total_by_category(expenses)
print()
print("By category")
for category, total in totals.items():
print(f"{category:<24}{total:>8,}")
def save_expenses(expenses):
"""Write every expense to EXPENSES_FILE, replacing what was there."""
with open(EXPENSES_FILE, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=FIELDS)
writer.writeheader()
writer.writerows(expenses)
def load_expenses():
"""Return the saved expenses, or an empty list if there is no file yet."""
if not EXPENSES_FILE.exists():
return []
expenses = []
with open(EXPENSES_FILE, newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
row["amount"] = int(row["amount"])
expenses.append(row)
return expenses
def main():
expenses = load_expenses()
if expenses:
print(f"Loaded from {EXPENSES_FILE}: {len(expenses)} expense(s).")
else:
print("No saved expenses yet. Starting a new list.")
budget = ask_for_amount("Monthly budget: ")
while True:
expense = ask_for_expense()
if expense is None:
break
expenses.append(expense)
save_expenses(expenses)
print(f"Saved to {EXPENSES_FILE}: {len(expenses)} expense(s).")
print_summary(expenses)
left = budget - total_spent(expenses)
print()
if left < 0:
print(f"Warning: over budget by {currency} {-left:,}")
elif left < budget / 10:
print(f"Careful: only {currency} {left:,} left")
else:
print(f"You have {currency} {left:,} left this month.")
if __name__ == "__main__":
main()
PYThe new function is ask_for_amount(prompt):
while True:repeats forever. The only way out is thereturnat the bottom.answer = input(prompt).strip()asks the question passed in aspromptand removes spaces from both ends, so the error message shows exactly what was typed.- In the
tryblock,int(answer)either works or raises aValueError. - Under
except ValueError:, the program says what went wrong and gives an example of a good answer.continuejumps back to the top of the loop, so the question is asked again. if amount <= 0:catches the numbers that are valid to Python but wrong for a budget: zero and anything negative. It also prints a message and usescontinue.return amountonly runs when both checks passed. It ends the loop and hands the number back to whoever called the function.
Because it takes the prompt as a parameter, the same function asks for the budget (ask_for_amount("Monthly budget: ") in main()) and for each expense (ask_for_amount("Amount: ") in ask_for_expense()). You wrote the checking once and use it twice.
The other changes:
- The comment on the first line now says part 8.
DEFAULT_CATEGORY = "other"near the top is a constant: a variable you set once and never change. Writing it in capital letters is how Python programmers say "do not change this while the program runs".- In
ask_for_expense(), the category prompt now shows the default in square brackets,Category [other]: `, a common way to tell people what pressing Enter will give them. `.strip()now removes spaces from the ends of the category before.lower(), soFood ` and `foodland in the same total. If the answer is empty (category == ""), the category becomes"other"instead of being saved as a blank.
Now try every kind of bad answer in one run. This types 50 000 (with a space) as the budget, then 50000, then an expense with abc, -200, 0 and 1,500 before the real amount, then a second expense with a blank category:
printf '50 000\n50000\nBus fare\ntransport\nabc\n-200\n0\n1,500\n1500\nAirtime\n\n1000\ndone\n' | python3 budget.py
cat expenses.csvCheck it worked
The program never crashes. Each bad answer gets a message and the question again:
Loaded from expenses.csv: 1 expense(s).
Monthly budget: '50 000' is not a whole number. Type digits only, like 1500.
Monthly budget: Item (or done): Category [other]: Amount: 'abc' is not a whole number. Type digits only, like 1500.
Amount: The amount must be more than 0.
Amount: The amount must be more than 0.
Amount: '1,500' is not a whole number. Type digits only, like 1500.
Amount: Item (or done): Category [other]: Amount: Item (or done): Saved to expenses.csv: 3 expense(s).The summary table that follows ends with 3 expenses, spent 6,500, the three categories and You have NGN 43,500 left this month.
The prompts run together because printf typed the answers, as before. expenses.csv now has three rows under the header: Rice,food,4000, Bus fare,transport,1500 and Airtime,other,1000. The blank category was saved as other.
Step 4 · Add a monthly report and a menu
So far the tracker does one thing per run: it asks for expenses, then prints a summary. A finished tool should let you choose. This version opens with a menu: a to add expenses, r to see a monthly report, q to quit. It also saves after every expense and exits politely if you stop it with Ctrl+C. Replace budget.py with the finished program:
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 8)
import csv
from pathlib import Path
currency = "NGN"
EXPENSES_FILE = Path("expenses.csv")
FIELDS = ["item", "category", "amount"]
DEFAULT_CATEGORY = "other"
def ask_for_amount(prompt):
"""Ask until the answer is a whole number above 0, then return it."""
while True:
answer = input(prompt).strip()
try:
amount = int(answer)
except ValueError:
print(f"'{answer}' is not a whole number. Type digits only, like 1500.")
continue
if amount <= 0:
print("The amount must be more than 0.")
continue
return amount
def ask_for_expense():
"""Ask for one expense. Return it as a dictionary, or None after done."""
item = input("Item (or done): ")
if item.strip().lower() == "done":
return None
category = input(f"Category [{DEFAULT_CATEGORY}]: ").strip().lower()
if category == "":
category = DEFAULT_CATEGORY
amount = ask_for_amount("Amount: ")
return {"item": item, "category": category, "amount": amount}
def total_spent(expenses):
"""Return the sum of all the amounts."""
spent = 0
for expense in expenses:
spent += expense["amount"]
return spent
def total_by_category(expenses):
"""Return a dictionary of category name to amount spent."""
totals = {}
for expense in expenses:
category = expense["category"]
if category in totals:
totals[category] = totals[category] + expense["amount"]
else:
totals[category] = expense["amount"]
return totals
def print_summary(expenses):
"""Print the table, the biggest expense and the totals per category."""
print()
print("Spending summary")
print("-" * 32)
for expense in expenses:
print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
print("-" * 32)
print(f"{len(expenses)} expenses, spent {total_spent(expenses):,}")
if len(expenses) > 0:
biggest = expenses[0]
for expense in expenses:
if expense["amount"] > biggest["amount"]:
biggest = expense
print(f"Biggest: {biggest['item']} ({biggest['amount']:,})")
totals = total_by_category(expenses)
print()
print("By category")
for category, total in totals.items():
print(f"{category:<24}{total:>8,}")
def save_expenses(expenses):
"""Write every expense to EXPENSES_FILE, replacing what was there."""
with open(EXPENSES_FILE, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=FIELDS)
writer.writeheader()
writer.writerows(expenses)
def load_expenses():
"""Return the saved expenses, or an empty list if there is no file yet."""
if not EXPENSES_FILE.exists():
return []
expenses = []
with open(EXPENSES_FILE, newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
row["amount"] = int(row["amount"])
expenses.append(row)
return expenses
def print_balance(expenses, budget):
"""Print what is left of the budget, with a warning when it runs low."""
left = budget - total_spent(expenses)
print()
if left < 0:
print(f"Warning: over budget by {currency} {-left:,}")
elif left < budget / 10:
print(f"Careful: only {currency} {left:,} left")
else:
print(f"You have {currency} {left:,} left this month.")
def print_report(expenses, budget):
"""Print the summary, each category's share of the budget and the balance."""
print_summary(expenses)
print()
print("Share of budget")
for category, total in total_by_category(expenses).items():
share = total * 100 // budget
print(f"{category:<24}{share:>7}%")
print_balance(expenses, budget)
def add_expenses(expenses):
"""Ask for expenses until done, saving the file after each one."""
while True:
expense = ask_for_expense()
if expense is None:
break
expenses.append(expense)
save_expenses(expenses)
print(f"Saved {expense['item']}: {expense['amount']:,} ({expense['category']})")
def main():
expenses = load_expenses()
if expenses:
print(f"Loaded from {EXPENSES_FILE}: {len(expenses)} expense(s).")
else:
print("No saved expenses yet. Starting a new list.")
budget = ask_for_amount("Monthly budget: ")
while True:
choice = input("[a]dd, [r]eport or [q]uit: ").strip().lower()
if choice == "a":
add_expenses(expenses)
elif choice == "r":
print_report(expenses, budget)
elif choice == "q":
print("Goodbye. Your expenses are saved.")
break
else:
print("Please type a, r or q.")
if __name__ == "__main__":
try:
main()
except (KeyboardInterrupt, EOFError):
print("\nStopped. Everything you added before this is saved.")
PYWhat is new, function by function:
add_expenses(expenses)is the old loop frommain(), moved into its own function. Instead of saving once afterdone, it callssave_expenses(expenses)straight after eachappend, so nothing you have entered is lost if the program stops halfway, and it confirms each expense with aSaved ...line.print_balance(expenses, budget)holds the lines from the end of part 7'smain()that work out what is left and print the message about it, unchanged. Giving them a name lets the report call them.print_summary(expenses)is unchanged too.print_report(expenses, budget)prints the summary from part 6, then each category's share of the budget, then the balance.shareis each category's total as a percentage of the budget, worked out with//so it stays a whole number, as in part 3.{category:<24}{share:>7}%uses the same widths as theBy categorylines, so the%signs sit in the column of the last digits above.main()loads the saved expenses, asks for the budget, then loops over the menu. Any answer other thana,rorqgetsPlease type a, r or q.and the menu again. That is the same idea asask_for_amount: never crash, always say what is expected.
The last block keeps the if __name__ == "__main__": guard from parts 6 and 7, which runs main() only when you start the file directly. What is new is the try and except (KeyboardInterrupt, EOFError) around main():
- The
tryaroundmain()catches two exceptions, listed in brackets afterexcept.KeyboardInterruptis what Ctrl+C raises.EOFError(end of file) is whatinput()raises when there is nothing more to read: when you press Ctrl+D (Ctrl+Z then Enter on Windows), or when piped input runs out. Instead of a traceback, the program prints one calm line. Because every expense is saved as soon as it is entered, that line is true.
Run a whole session: an answer the menu does not know, a report, one new expense, another report, then quit:
printf '50000\nx\nr\na\nData bundle\nAirtime\n2000\ndone\nr\nq\n' | python3 budget.pyThen stop the program partway through an expense. Here the input runs out after Taxi, which is the same as pressing Ctrl+D at the Category prompt:
printf '50000\na\nTaxi\n' | python3 budget.pyCheck it worked
The first run prints the menu after each action. Each report is the summary table from part 6 followed by the shares and the balance. The second report has a Data bundle row in the table, 4 expenses, spent 8,500, and ends like this:
Share of budget
food 8%
transport 3%
other 2%
airtime 4%
You have NGN 41,500 left this month.The category is airtime, not Airtime, because ask_for_expense() lowers it, so Airtime and airtime always land in the same total. The second run ends with Stopped. Everything you added before this is saved. and no traceback. Run python3 budget.py yourself, choose a and press Ctrl+C at any prompt to see the same message.
Step 5 · Test total_by_category with pytest
Every time you changed the tracker in this series, you checked it by running it and reading the output. That works, but it gets slow, and it is hard to remember every case. A test is a small piece of code that runs your code and checks the answer for you. pytest is a widely used tool for running tests in Python. The full setup is covered in How to write and run tests in Python with pytest; here you need only the basics.
pytest is not part of Python, so install it into a virtual environment: a folder, .venv, that holds packages for this project only, without changing the rest of your computer. The download is under 2 MB, which matters if you are on prepaid mobile data.
python3 -m venv .venv
.venv/bin/python -m pip install --quiet pytest==9.2.0
.venv/bin/python -m pytest --versionpython3 -m venv .venvcreates the virtual environment..venv/bin/pythonis the copy of Python inside it. Running-m pip installwith that copy installs pytest into.venvand nowhere else.==9.2.0pins the version, so you get the same pytest this tutorial was written with.- On Windows the path is
.venv\Scripts\pythoninstead of.venv/bin/python. With uv,uv run --with pytest==9.2.0 pytestdoes the same without making.venvyourself.
Now write the tests. pytest looks for files whose names start with test_, and runs every function in them whose name starts with test_:
cat > test_budget.py <<'PY'
from budget import total_by_category
def test_adds_up_expenses_in_the_same_category():
expenses = [
{"item": "Bus fare", "category": "transport", "amount": 300},
{"item": "Taxi", "category": "transport", "amount": 1200},
]
assert total_by_category(expenses) == {"transport": 1500}
def test_keeps_different_categories_apart():
expenses = [
{"item": "Rice", "category": "food", "amount": 4000},
{"item": "Data bundle", "category": "airtime", "amount": 2000},
{"item": "Tomatoes", "category": "food", "amount": 1500},
]
assert total_by_category(expenses) == {"food": 5500, "airtime": 2000}
def test_no_expenses_gives_no_totals():
assert total_by_category([]) == {}
PY
.venv/bin/python -m pytest -vfrom budget import total_by_categoryloadsbudget.pyand takes the one function the tests need. This is theif __name__ == "__main__":guard from part 6 at work:main()does not run on import. Without that line, the import would callinput(), and pytest would stop with an error saying something like "reading from stdin while output is captured".- Each test builds a small list of expenses by hand, the same shape
ask_for_expense()produces. assertchecks that something is true.assert total_by_category(expenses) == {"transport": 1500}says "the totals must be exactly this dictionary". If they are, the test passes silently. If not, pytest shows you both values.- The third test checks the edge case from parts 5 and 6: no expenses at all should give an empty dictionary, not an error.
-v(verbose) prints the name of each test as it runs. Long, descriptive names are normal for tests, so the output reads like a list of what the code does.
Check it worked
The first command prints pytest 9.2.0. The test run ends with three PASSED lines and a summary like this (your timing will differ):
test_budget.py::test_adds_up_expenses_in_the_same_category PASSED [ 33%]
test_budget.py::test_keeps_different_categories_apart PASSED [ 66%]
test_budget.py::test_no_expenses_gives_no_totals PASSED [100%]
============================== 3 passed in 0.01s ===============================To see a failure, change + expense["amount"] in total_by_category to - expense["amount"], run .venv/bin/python -m pytest again, and read how pytest shows the expected and actual dictionaries side by side. Change it back and run the tests once more before you carry on.
Step 6 · Write a README
A README is a short text file that tells someone what a program does and how to use it. That someone is often you, six months from now. Markdown, the format of README.md, is plain text with a few conventions: # starts a heading and - starts a list item. Create it:
cat > README.md <<'TXT'
# Budget tracker
A small command-line budget tracker written in Python 3.15 while following
the Padding series "Learn to program from zero".
## What it does
- Asks for your monthly budget, then offers a menu: add expenses, see a
report, or quit.
- Saves every expense to expenses.csv as soon as you enter it, so nothing
is lost if the program is stopped.
- The report shows every expense, the biggest one, the total and share of
the budget per category, and whether you are on track, close to the
limit or over budget.
- Amounts are whole numbers in your own currency. Letters, commas,
decimals, zero and negative numbers are refused and asked for again.
- A blank category is saved as "other".
## Run it
python3 budget.py
## Run the tests
python3 -m venv .venv
.venv/bin/python -m pip install pytest==9.2.0
.venv/bin/python -m pytest
## Files
- budget.py: the program.
- test_budget.py: tests for total_by_category.
- expenses.csv: your saved expenses (item, category, amount). It opens in
any spreadsheet app.
TXTThe commands are indented by four spaces. In Markdown, that shows them as code, set apart from the text.
Check it worked
Run cat README.md and read it through as if you had never seen the program. You should be able to answer three questions from it alone: what the program does, how to start it, and how to run the tests. If one of the answers is missing, add it. Code hosting sites such as GitHub show README.md on a project's front page, so this file is what visitors see first when you share your code.
Step 7 · Review the finished program and plan what to add
Count the lines and list the files you have made:
wc -l budget.py
lswc -l counts lines. ls lists the folder.
Look back at where you started. In part 1, budget.py was a handful of variables and a print. It now reads input safely, makes decisions, loops, stores records in a list of dictionaries, is organised into functions, keeps its data in a file between runs, and has tests and documentation. Those are the building blocks of almost every program you will ever write, in Python or any other language.
The tracker is yours now. Here are ideas to extend it, roughly from easiest to hardest. Each one uses only what you have learned in this series:
- Press Enter at the
Item (or done):prompt and an expense with no name is saved. Make it ask again, the wayask_for_amountdoes. - Add a
dmenu option that deletes the last expense, for when you type the wrong one, and saves the list. - Add a fourth test for
total_by_categorywith an expense whose category has capital letters, and decide what the right answer should be. - Save the budget in a small file too, so you do not type it every time.
- Add a
datecolumn toexpenses.csv(Python'sdatetimemodule gives today's date) and make the report show only the current month. Load older files that have no date column without crashing. - Show your
currencycode on the amounts in the table and the report, not only in the balance message.
If you would rather start again from an empty folder one day, the command below deletes the whole ~/budget-tracker folder and everything in it: the program, the tests, expenses.csv, expenses-part7.csv with your part 7 expenses, and PLAN.txt and branch-tests.txt if you made them in parts 1 and 3. Only run it when you no longer want the tracker or any of its data:
cd ~
rm -rf ~/budget-trackerCheck it worked
wc -l budget.py prints 162 and the file name: about 160 lines of program, counting the docstrings and the blank lines between functions. ls shows README.md, budget.py, expenses.csv and test_budget.py (plus expenses-part7.csv, PLAN.txt and branch-tests.txt if you came through the earlier parts), and a __pycache__ folder that Python made when the tests imported budget.py. The .venv folder is there too but hidden, because its name starts with a dot; ls -a shows it. If you ran the last command, ls ~/budget-tracker now says the folder does not exist.
Next steps
- Go deeper into exceptions: catching several kinds,
elseandfinally, and raising your own: handle errors with try and except in Python. - Learn more of pytest, including running many cases from one test and testing code that reads files: how to write and run tests in Python with pytest.
- Store the tracker's data as JSON instead of CSV, and handle a damaged data file: how to read and write files and JSON in Python.
- Review how the tracker saves and loads its expenses: save expenses to a CSV file and load them next time.
Part of these paths
Related tutorials
- Save expenses to a CSV file and load them next timeYou will add save_expenses() and load_expenses() to the budget tracker so every expense is kept in expenses.csv between runs, the first run starts cleanly, and the file opens in any spreadsheet.
- Handle errors with try and except in PythonYou will break a small file-averaging script three ways on purpose, then catch each error by name, raise your own clear errors, and end with a script that reports exactly what went wrong and exits with the right status.
- How to Write and Run Tests in Python with pytestYou will install pytest 9.2 in a uv project, write tests for a small price-parsing module, run many cases from one test with parametrize, read a failure and fix the code, and use a fixture that gives each test its own temporary folder.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials