Skip to main content

Programming fundamentals · Beginner · 14 min

Keep asking for expenses until the user is done

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

You will turn the budget tracker into a program that asks for expense after expense with a while loop, stops when you type done, and prints the total, how many expenses you entered and what is left.

On this page

So far the budget tracker asks for one expense and stops. Real spending does not come one item at a time: in a week you might pay for transport, airtime, lunch and a gas refill. Running the program once per expense and adding the results in your head defeats the point of writing it.

In this part you teach the program to repeat itself. A while loop runs the same lines again and again for as long as a condition is true. You will watch a loop count down, write one that never stops (on purpose, so you know what it looks like and how to stop it), and then rebuild the tracker so it keeps asking for expenses until you type done. At the end it prints the total, how many expenses you entered and the balance left, and still warns you when you overspend.

This is part 4 of Learn to program from zero. Every command uses python3; if your command is python3.15 or py, type that instead.

Step 1 · Start from the part 3 tracker

Open a terminal in the ~/budget-tracker folder you have used since part 1.

The next command writes the part 3 version of budget.py, replacing what is in the file now. If you want to keep your own version, copy it first (for example to budget-part3.py) or skip the command and compare your file with the lines between the two PY markers. You can also paste those lines into your editor instead of running the command.

Bash
mkdir -p ~/budget-tracker
cd ~/budget-tracker
cat > budget.py <<'PY'
budget = int(input("Monthly budget: "))
spent = int(input("Amount spent: "))
balance = budget - spent
low_mark = budget // 10

if balance < 0:
    print(f"Warning: you are {-balance} over budget.")
elif balance < low_mark:
    print(f"Careful: only {balance} left, less than 10% of your budget.")
else:
    print(f"Balance: {balance} left of {budget}.")
PY

Each line is what you built in parts 2 and 3: two questions, each answer turned into a whole number with int(), a subtraction, low_mark = budget // 10 for 10% of the budget (// keeps the result a whole number), and an if/elif/else that picks one of three messages. Amounts are whole units of your currency (naira, cedis, shillings, rand, pounds), so 50000 means fifty thousand.

Run it and answer the two questions with 50000 and 12500:

Bash
python3 budget.py

Check it worked

The last line printed is Balance: 37500 left of 50000. The program then ends and your terminal prompt comes back: it asked for exactly one expense. That is the limit you remove in this tutorial.

Step 2 · Watch a while loop count down

Before you change the tracker, see a loop on its own. Create countdown.py in the same folder:

Bash
cat > countdown.py <<'PY'
count = 3
while count > 0:
    print(count)
    count = count - 1
print("Go")
PY
python3 countdown.py

Line by line:

  • count = 3 creates a variable that the loop will change.
  • while count > 0: is the loop. Python checks the condition count > 0. If it is true, Python runs the indented lines below it, then comes back to this line and checks again. When the condition is false, Python skips the indented lines and carries on after them. The colon at the end is required, as it is after if.
  • print(count) and count = count - 1 are the loop body: the indented block that repeats. The second line works out count - 1 and stores the result back in count, so the number goes down by one each time round.
  • print("Go") is not indented, so it is not part of the loop. It runs once, after the loop has finished.

Each pass through the body is called an iteration. This loop has three: count is 3, then 2, then 1. On the fourth check count is 0, 0 > 0 is false, and the loop ends.

Check it worked

The output is four lines: 3, 2, 1 and Go. Change the first line to count = 5 and run it again: you see five numbers before Go. Change it to count = 0 and you see only Go, because the condition is false the first time it is checked, so the body never runs at all. Set it back to 3 before moving on.

Step 3 · Write a loop that never stops, and stop it

The line count = count - 1 is what makes the countdown end. Leave it out and the condition never becomes false. Create forever.py with that line missing:

Bash
cat > forever.py <<'PY'
count = 3
while count > 0:
    print(count)
print("Go")
PY

Read the program before you run it and predict what happens. count is 3, 3 > 0 is true, so Python prints 3, comes back to the while line, checks 3 > 0 again, and so on. Nothing inside the loop ever changes count. This is an infinite loop, and it is the most common loop bug there is.

Run it, let it print for a second or two, then hold the Ctrl key and press C:

Bash
python3 forever.py

Ctrl+C sends an interrupt to the running program. Python stops whatever line it is on and prints a short traceback, the report it gives when a program stops because of an error. The same key works in the macOS and Linux terminals and in Windows Terminal, PowerShell and Command Prompt. If you are following along in Termux on an Android phone, tap CTRL in the extra keys row above the keyboard, then C.

print("Go") never runs. The program did not reach the end; you stopped it from outside.

Check it worked

Your terminal filled with 3 on every line until you pressed Ctrl+C. After that, the last lines look something like this, with your own folder in the path and possibly a different line number:

Text
Traceback (most recent call last):
  File "/home/you/budget-tracker/forever.py", line 3, in <module>
    print(count)
KeyboardInterrupt

The word that matters is KeyboardInterrupt: it means you stopped the program, not that the code has a syntax mistake. Your prompt is back and you can type commands again. Whenever a program of yours seems stuck, Ctrl+C is the first thing to try.

You are done with the two practice files, so delete them and keep the folder for the tracker:

Bash
rm countdown.py forever.py

Step 4 · Keep asking until the user types done

Now use a loop in the tracker. The program cannot know in advance how many expenses you have, so instead of counting down it keeps going until you tell it to stop. Replace budget.py with this version:

Bash
cat > budget.py <<'PY'
budget = int(input("Monthly budget: "))
spent = 0

while True:
    answer = input("Expense (or done): ")
    if answer == "done":
        break
    spent = spent + int(answer)
    print(f"Running total: {spent}")

balance = budget - spent
low_mark = budget // 10

if balance < 0:
    print(f"Warning: you are {-balance} over budget.")
elif balance < low_mark:
    print(f"Careful: only {balance} left, less than 10% of your budget.")
else:
    print(f"Balance: {balance} left of {budget}.")
PY

What is new:

  • spent = 0 starts the running total at zero before the loop. Each expense is added to it. If you created spent inside the loop instead, it would be reset to zero on every pass and the total would be lost.
  • while True: is a loop whose condition is always true. On its own that is the infinite loop from the previous step. The difference is the next lines, which give it a way out.
  • answer = input("Expense (or done): ") asks the question again on every pass. The answer is kept as text for now, because it might be the word done rather than a number.
  • if answer == "done": compares the text with the word done. Two equals signs compare; one equals sign stores a value.
  • break ends the loop immediately. Python jumps to the first line after the loop body, balance = budget - spent, and the rest of the program runs as before.
  • spent = spent + int(answer) only runs when the answer was not done. It converts the text to a whole number and adds it to the total.
  • print(f"Running total: {spent}") shows the total after each expense, so you can see the loop working.

The lines after the loop are the same as in part 3: balance, low_mark and the if/elif/else with its three messages. They now judge the total of every expense instead of a single one.

Run it. Answer 50000 for the budget, then enter 1500, 12000 and 800, then type done:

Bash
python3 budget.py

Check it worked

You are asked Expense (or done): after every amount, not just once. The running totals are 1500, 13500 and 14300, and after done the last line is Balance: 35700 left of 50000. Run it again and enter as many expenses as you like: ten, twenty, or none at all.

Step 5 · Count the expenses and print a summary

A total on its own hides how you got there. Add a second variable that counts how many expenses were entered, and print a summary line once the loop ends. Replace budget.py again:

Bash
cat > budget.py <<'PY'
budget = int(input("Monthly budget: "))
spent = 0
count = 0

while True:
    answer = input("Expense (or done): ")
    if answer == "done":
        break
    spent += int(answer)
    count += 1
    print(f"Running total: {spent}")

balance = budget - spent
low_mark = budget // 10
print(f"Expenses entered: {count}, total {spent}.")

if balance < 0:
    print(f"Warning: you are {-balance} over budget.")
elif balance < low_mark:
    print(f"Careful: only {balance} left, less than 10% of your budget.")
else:
    print(f"Balance: {balance} left of {budget}.")
PY

The changes:

  • count = 0 starts the counter before the loop, for the same reason spent starts there.
  • spent += int(answer) is a shorter way to write spent = spent + int(answer). The += operator means "add this to the variable and store the result back in it". Programmers use it so often that you will see it in almost every loop.
  • count += 1 adds one to the counter each time an expense is accepted. It sits after the break check, so typing done is not counted as an expense.
  • print(f"Expenses entered: {count}, total {spent}.") is not indented, so it runs once, after the loop. It is worded as a label and a number, so it reads correctly whether you entered 0, 1 or 20 expenses.

Try three runs, each designed to reach a different message. Press Enter after each answer:

  • Budget 50000, then 1500, 12000, 800, done: you should see Balance: 35700 left of 50000.
  • Budget 50000, then 30000, 16000, done: you should see Careful: only 4000 left, less than 10% of your budget.
  • Budget 50000, then 30000, 25000, done: you should see Warning: you are 5000 over budget.
Bash
python3 budget.py

Check it worked

Each run ends with the message listed for it, and just above it a line such as Expenses entered: 3, total 14300. Now try one more run where you type done straight after the budget: the summary says Expenses entered: 0, total 0. and the program does not crash. The loop body ran zero times, which is a normal outcome for a loop, not an error.

Step 6 · Accept Done, DONE and stray spaces

People do not type exactly what you expect. Run the tracker, enter a budget and one expense, then type Done with a capital D:

Bash
python3 budget.py

The program crashes with a traceback ending in something like ValueError: invalid literal for int() with base 10: 'Done'. To Python, "Done" and "done" are different pieces of text, so the if did not match, the loop carried on to int(answer), and int() cannot turn a word into a number. On a phone keyboard, which often capitalises the first letter for you, this happens a lot.

Fix it by tidying the answer before comparing it. Replace budget.py with the finished version for this part:

Bash
cat > budget.py <<'PY'
budget = int(input("Monthly budget: "))
spent = 0
count = 0

while True:
    answer = input("Expense (or done): ").strip().lower()
    if answer == "done":
        break
    spent += int(answer)
    count += 1
    print(f"Running total: {spent}")

balance = budget - spent
low_mark = budget // 10
print(f"Expenses entered: {count}, total {spent}.")

if balance < 0:
    print(f"Warning: you are {-balance} over budget.")
elif balance < low_mark:
    print(f"Careful: only {balance} left, less than 10% of your budget.")
else:
    print(f"Balance: {balance} left of {budget}.")
PY

Only one line changed. .strip() removes spaces from the start and end of the text, and .lower() turns capital letters into small ones. They run left to right, so " DONE " becomes "DONE" and then "done", which matches. Numbers are unaffected: "1500" stays "1500".

Typing letters, a comma (1,500) or a decimal point as an expense still crashes the program with a ValueError. That is fine for now: part 8 makes the tracker ask again instead of crashing.

Check it worked

Run the tracker and finish with Done, then again with DONE typed after a couple of spaces. Both times the loop ends cleanly and you see the summary line, for example Expenses entered: 1, total 1500., followed by the balance message. Your budget.py now matches the file above. Keep it and the ~/budget-tracker folder: this is where part 4 ends.

Next steps

You now have a tracker that accepts any number of expenses. It only remembers the total, though, so it cannot tell you what the biggest expense was or how much went on transport.

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.