Skip to main content

Programming fundamentals · Beginner · 22 min

Organise the budget tracker into functions

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will split the fifty-line budget tracker into ask_for_expense, total_spent, total_by_category, print_summary and main, proving after every move that it still prints exactly the same summary.

On this page

At the end of part 5 your tracker does a lot: it asks for a budget, collects any number of expenses, and prints a table of them, the number of expenses and the total spent, the biggest expense, a total per category and a message about what is left in naira. It is also about fifty lines in one long block. To change how the summary looks you have to scroll past the questions, and to check the category totals you have to run the whole program and type every answer again.

In this part you fix that without changing what the program does. You cut the script into functions: named blocks of code that each do one job. You move one block at a time, and after every move you run the tracker on the same answers and compare its output with the original, so you know at once if something broke. Programmers call this kind of change, where the behaviour stays the same and the code gets clearer, refactoring.

You end with a main() function that reads like a list of steps, and you try your functions on their own in the Python REPL. Nothing is downloaded in this part, so it costs no data if you are on a prepaid bundle.

The examples use python3, as in the earlier parts. On Windows outside WSL, type py instead.

Step 1 · Start from the part 5 tracker and record what it prints

Go to the tracker folder. If you finished part 5, make a copy of your own version first, so you can come back to it:

Bash
cd ~/budget-tracker
cp budget.py budget_mine_part5.py

So that every step below matches your screen line for line, this tutorial starts from the finished part 5 tracker, exactly as part 5 left it. If you followed part 5 to the end, your budget.py is already this file. The next command writes it to budget.py anyway; if you are starting the series here, this is your starting file:

Bash
mkdir -p ~/budget-tracker
cd ~/budget-tracker
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 5)
currency = "NGN"
budget = int(input("Monthly budget: "))

expenses = []

while True:
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        break
    category = input("Category: ").lower()
    amount = int(input("Amount: "))
    expense = {"item": item, "category": category, "amount": amount}
    expenses.append(expense)

print()
print("Spending summary")
print("-" * 32)

spent = 0
for expense in expenses:
    print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    spent += expense["amount"]

print("-" * 32)
print(f"{len(expenses)} expenses, spent {spent:,}")

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 = {}
for expense in expenses:
    category = expense["category"]
    if category in totals:
        totals[category] = totals[category] + expense["amount"]
    else:
        totals[category] = expense["amount"]

print()
print("By category")
for category, total in totals.items():
    print(f"{category:<24}{total:>8,}")

left = budget - spent
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.")
PY

Every idea in it comes from parts 1 to 5: input() and int(), a while loop that stops at done, a list of dictionaries, .lower() so Food and food count as one category, f-string widths for the table, a second dictionary of totals per category, and if/elif/else for the message at the end.

Now save a set of answers in a file, so you can give the program the same input every time without typing it. They are the six expenses from part 5:

Bash
printf '%s\n' 50000 'Bus fare' travel 1500 Lunch Food 2500 Rent housing 20000 'Data bundle' phone 3000 Groceries food 6000 Taxi travel 2000 done > test-input.txt
python3 budget.py < test-input.txt > before.txt
cat before.txt

What each part does:

  • printf '%s\n' ... prints each word or quoted phrase after it on its own line, as if you pressed Enter after each one, as in part 5. The answers are a budget of 50000, six expenses (three answers each), then done. > test-input.txt saves that text in a file instead of showing it.
  • python3 budget.py < test-input.txt runs the tracker and feeds it the file as if you were typing. < means "read the keyboard input from this file".
  • > before.txt saves everything the program prints into before.txt. This file is your record of the correct behaviour.

Check it worked

cat before.txt starts with one long line of prompts run together (Monthly budget: Item (or done): Category: ...), because nobody pressed Enter on screen. Then comes the summary:

Text
Spending summary
--------------------------------
Bus fare      travel       1,500
Lunch         food         2,500
Rent          housing     20,000
Data bundle   phone        3,000
Groceries     food         6,000
Taxi          travel       2,000
--------------------------------
6 expenses, spent 35,000
Biggest: Rent (20,000)

By category
travel                     3,500
food                       8,500
housing                   20,000
phone                      3,000

You have NGN 15,000 left this month.

Step 2 · Move the category totals into total_by_category()

Start with the block that is easiest to lift out: the one that builds totals. It needs one thing, the list of expenses, and produces one thing, the dictionary of totals. That makes it a natural function.

Write the new version of budget.py. The function goes near the top, and the old block is replaced by one line that calls it:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 6)
currency = "NGN"


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


budget = int(input("Monthly budget: "))

expenses = []

while True:
    item = input("Item (or done): ")
    if item.strip().lower() == "done":
        break
    category = input("Category: ").lower()
    amount = int(input("Amount: "))
    expense = {"item": item, "category": category, "amount": amount}
    expenses.append(expense)

print()
print("Spending summary")
print("-" * 32)

spent = 0
for expense in expenses:
    print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    spent += expense["amount"]

print("-" * 32)
print(f"{len(expenses)} expenses, spent {spent:,}")

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,}")

left = budget - spent
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.")
PY

The new parts, line by line:

  • def total_by_category(expenses): defines a function. def is short for define, total_by_category is the name you choose, and the colon starts the indented block that belongs to it, exactly like the colon after while or if.
  • expenses inside the brackets is a parameter: a name for the value the function is handed when it is called. Inside the function, expenses means "whatever list was passed in".
  • The line in triple quotes is a docstring, a one-line description of the function. Python stores it, and tools show it when you ask for help on the function.
  • The loop is the same code as before, moved four spaces to the right so that it sits inside the function.
  • return totals hands the finished dictionary back to whoever called the function, and ends the function there.
  • Defining a function does not run it. Python reads the def block, remembers it, and carries on. The code inside runs only at totals = total_by_category(expenses), where the list goes in and the returned dictionary is stored in totals.

The two blank lines before and after a function are a Python style convention. They make each function easy to spot; Python itself does not need them.

Now run the tracker on the same answers and compare:

Bash
python3 budget.py < test-input.txt > after.txt
diff before.txt after.txt && echo "Same output"

diff compares two files and prints only the lines that differ. When they match it prints nothing, and && echo "Same output" then prints a confirmation. && means "run the second command only if the first one succeeded".

Check it worked

You see Same output and nothing else. If diff prints lines starting with < and >, those are the old and new versions of a line that changed: compare your file with the block above, looking first at indentation inside the function and the return totals line.

Step 3 · Move the questions into ask_for_expense()

Next, the questions inside the loop. Each time round, the loop asks three things and builds one expense. That becomes ask_for_expense(), which takes no parameters and returns one expense. The awkward part is done: the function needs a way to say "there is no expense, the user has finished". Python's answer is None, a special value that means "nothing here".

Write the next version:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 6)
currency = "NGN"


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_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


budget = int(input("Monthly budget: "))

expenses = []

while True:
    expense = ask_for_expense()
    if expense is None:
        break
    expenses.append(expense)

print()
print("Spending summary")
print("-" * 32)

spent = 0
for expense in expenses:
    print(f"{expense['item']:<14}{expense['category']:<10}{expense['amount']:>8,}")
    spent += expense["amount"]

print("-" * 32)
print(f"{len(expenses)} expenses, spent {spent:,}")

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,}")

left = budget - spent
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.")
PY

What changed:

  • def ask_for_expense(): has empty brackets: this function needs nothing from outside, because it gets its information from the keyboard.
  • return None runs when the user types done, in any capitals, as in part 5. A function stops at the first return it reaches, so the two questions below it are skipped.
  • .lower() moved into the function with the `Category: ` question, so every expense it returns already has a lower-case category.
  • The last line, return {...}, builds the dictionary and hands it back in one go, instead of storing it in expense first.
  • In the loop, expense = ask_for_expense() stores whatever came back. if expense is None: checks for the "finished" signal; is None is how Python code tests for None. Otherwise the expense goes on the list.

The loop is now four short lines, and the word break sits right next to the reason for it.

Bash
python3 budget.py < test-input.txt > after.txt
diff before.txt after.txt && echo "Same output"

Check it worked

You see Same output. The prompts are identical too, because they live inside ask_for_expense() with the same text, and diff compares them as well.

Step 4 · Move the report into total_spent() and print_summary()

The report has two parts: the summary (the table, the count, the biggest expense and the category totals) and, at the very end, the message about what is left. The message needs the budget; the summary does not. So the summary becomes one function, print_summary(expenses), and the message stays outside it for now.

There is one snag. The table loop also adds up spent, and the message at the end needs spent too. If you moved that loop into print_summary(), spent would be trapped inside the function. The fix is a small function whose only job is to work out the total and return it, so any part of the program can ask for it:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 6)
currency = "NGN"


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,}")


budget = int(input("Monthly budget: "))

expenses = []

while True:
    expense = ask_for_expense()
    if expense is None:
        break
    expenses.append(expense)

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.")
PY

What to notice:

  • total_spent(expenses) returns a number. It is called twice: inside print_summary() for the 6 expenses, spent 35,000 line, and at the bottom of the file to work out left. Writing the sum once and calling it twice means you can never get two different totals.
  • print_summary() calls total_spent() and total_by_category(). Functions can use other functions, which is how small pieces build up into a program.
  • print_summary() has no return. Its job is to print, not to work something out for later. A function without return hands back None when it finishes. The difference between printing a result and returning it matters a lot, and write functions that return values covers it in depth.
  • totals, biggest and the loop variables now live inside print_summary(). They are local variables: they exist while the function runs and disappear when it ends. Code outside the function cannot see them, which is exactly why spent needed its own function.
Bash
python3 budget.py < test-input.txt > after.txt
diff before.txt after.txt && echo "Same output"

Check it worked

You see Same output. The bottom of the file is now only the budget question, the loop, one call to print_summary(expenses) and the message about what is left.

Step 5 · Wrap the remaining steps in main()

The last loose code at the bottom of the file asks for the budget, collects expenses, prints the summary and says what is left: the plan of the whole program. Put it in a function called main(), then add two lines that call it. This is the final version for this part, and the file part 7 starts from:

Bash
cat > budget.py <<'PY'
# budget.py: a personal budget tracker (part 6)
currency = "NGN"


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 main():
    budget = int(input("Monthly budget: "))
    expenses = []
    while True:
        expense = ask_for_expense()
        if expense is None:
            break
        expenses.append(expense)

    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()
PY

The new parts:

  • def main(): holds the top-level steps. Read its body aloud and it is the program's plan: ask for the budget, collect expenses until done, print the summary, say what is left. The detail of each step is one function name away.
  • currency = "NGN" stays at the top of the file, outside every function. A variable set there can be read inside any function in the file, which is why main() can still use it. Change it to KES, GHS, ZAR or your own currency code in one place.
  • if __name__ == "__main__": checks how the file is being used. Python sets the hidden variable __name__ to "__main__" when you run the file with python3 budget.py. When another piece of code imports the file to borrow its functions, __name__ is "budget" instead, so main() does not run. You use that in the next step.
  • main() on the last line is the call that starts everything. Without it the file would define five functions and then stop, printing nothing.

Run the final comparison, and then run the tracker yourself with your own spending:

Bash
python3 budget.py < test-input.txt > after.txt
diff before.txt after.txt && echo "Same output"
Bash
python3 budget.py

Check it worked

The comparison prints Same output. Running the tracker by hand asks the same questions as in part 5 (Monthly budget: `, then `Item (or done): `, `Category: ` and `Amount: ` for each expense) and prints the same table and summary. The file is longer than before, because of the `def lines, docstrings and blank lines, but each job now has a name: you can find the summary code by looking for print_summary.

Step 6 · Try a function on its own in the REPL

Here is the pay-off. Because total_by_category() takes a list and returns a dictionary, and total_spent() takes a list and returns a number, you can check them without running the tracker or typing a single answer. Start the Python REPL (the interactive prompt) from the budget-tracker folder:

Bash
python3

At the >>> prompt, type the lines after each >>>. Python prints the result below:

Text
>>> from budget import total_by_category, total_spent
>>> trip = [{"item": "Bus", "category": "travel", "amount": 1500}, {"item": "Taxi", "category": "travel", "amount": 2000}]
>>> total_by_category(trip)
{'travel': 3500}
>>> total_spent(trip)
3500
>>> total_by_category([])
{}
>>> exit()

What happened:

  • from budget import total_by_category, total_spent loads budget.py and makes those two functions available. Thanks to the __name__ check, the tracker does not start and no questions appear.
  • trip is a small list you made up by hand, with two travel expenses.
  • total_by_category(trip) returns {'travel': 3500}: 1500 plus 2000, both in one category. The REPL shows dictionaries with single quotes; that is only how it displays them.
  • total_spent(trip) returns the plain number 3500, with no comma: the , in {spent:,} only formats a number when it is printed in an f-string.
  • total_by_category([]) checks the edge case of no expenses at all, and returns an empty dictionary instead of crashing.
  • exit() leaves the REPL.

You can run the same check as a one-line command, which is handy when you want to repeat it:

Bash
python3 -c 'from budget import total_by_category; print(total_by_category([{"item": "Bus", "category": "travel", "amount": 1500}, {"item": "Taxi", "category": "travel", "amount": 2000}]))'

python3 -c runs the Python code in quotes and exits. Semicolons separate the two statements on one line.

Importing budget.py also creates a __pycache__ folder next to it. Python keeps a compiled copy of the file there to load it faster next time. It is safe to ignore or delete.

Check it worked

The import line returns straight to >>> without asking for a budget, and the three calls print {'travel': 3500}, 3500 and {}. The one-line command prints {'travel': 3500}. If the import starts asking Monthly budget, the if __name__ == "__main__": lines are missing or main() is not indented under them.

Step 7 · Spot the three mistakes beginners make with functions

Make a scratch file so budget.py stays clean. It contains two classic mistakes:

Bash
cat > mistakes.py <<'PY'
def total_spent(expenses):
    total = 0
    for expense in expenses:
        total = total + expense["amount"]
    print(total)


result = total_spent([{"item": "Bread", "category": "food", "amount": 900}])
print(f"Result: {result}")
print(total)
PY

Run it:

Bash
python3 mistakes.py

You see 900, then Result: None, then a traceback ending in something like NameError: name 'total' is not defined. That is two mistakes:

  • Printing instead of returning. The function prints 900 but has no return, so it hands back None, and result is None. If you want to use a function's answer later, it must return it. Change print(total) inside the function to return total and result holds 900.
  • Using a local variable outside its function. total was created inside total_spent(), so it vanished when the function ended. The last line cannot see it. Use the returned value (result) instead.

The third mistake prints no error at all: forgetting the brackets. Writing main instead of main() on the last line of budget.py only names the function without calling it, so the program does nothing and exits quietly. If a script runs and prints nothing, check for the brackets first.

Remove the scratch files. Keep budget.py, which part 7 builds on:

Bash
rm -f mistakes.py before.txt after.txt test-input.txt
rm -rf __pycache__
ls

Check it worked

Running mistakes.py showed 900, Result: None and a NameError. After the clean-up, ls lists budget.py, plus PLAN.txt from part 1, branch-tests.txt from part 3 and any copies you kept (such as budget_mine_part5.py). python3 budget.py still runs the full tracker.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.