Programming fundamentals · Beginner · 14 min
Warn when spending goes over budget with if and else
By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim image (Debian)
You will teach your Python budget tracker to make decisions, so it warns you when you overspend, cautions you when less than a tenth of the budget is left, and otherwise shows the balance.
On this page
At the end of part 2 your budget tracker asks for your budget and one expense, then prints what is left. It does the same thing whatever you type. If you spend more than you have, it calmly prints a negative number and nothing else.
Real programs react to what happens. In this part you give the tracker three possible responses: a warning when the balance falls below zero, a caution when less than 10% of the budget is left, and the plain balance otherwise. On the way you meet comparison operators, the if, elif and else statements, and the rule that makes Python different from many languages: indentation is part of the code.
This is part 3 of the series Learn to program from zero. Amounts are whole units of your own currency, as in part 2: naira, shillings, rand, rupees, pounds or anything else. The examples use a monthly budget of 50000.
Step 1 · Start from the part 2 tracker
Open a terminal and go to the ~/budget-tracker folder you used for parts 1 and 2.
The next command writes budget.py exactly as it stood at the end of part 2, and it replaces whatever is in that file now. If you want to keep your own version, copy it first with cp budget.py budget-part2.py, or skip the command and compare your file with the lines between the two PY markers. If you are starting here, the command also creates the folder.
mkdir -p ~/budget-tracker
cd ~/budget-tracker
cat > budget.py <<'PY'
budget = int(input("Monthly budget: "))
spent = int(input("Amount spent: "))
balance = budget - spent
print(f"Budget {budget}, spent {spent}, left {balance}")
PYA quick reminder of what each line does:
input("Monthly budget: ")shows the prompt and waits for you to type something and press Enter. It always gives back text.int(...)turns that text into a whole number, so Python can do arithmetic with it. Type whole units of your currency.balance = budget - spentstores the result of the subtraction in a variable calledbalance.- The
printline uses an f-string: the parts in curly brackets are replaced with the values of those variables.
Run it and answer the two questions yourself:
python3 budget.pyIf you installed Python with uv as in hello-world-in-python, run uv run budget.py instead, here and in every later step.
Typing the same answers again and again gets slow once you test several cases. The shell can type them for you. printf prints text, \n is the Enter key, and the | symbol (a pipe) sends that text to your program as if you had typed it:
printf '50000\n12500\n' | python3 budget.pyCheck it worked
The interactive run prints Budget 50000, spent 12500, left 37500 after you type 50000 and 12500. The printf run prints all of it on one line:
Monthly budget: Amount spent: Budget 50000, spent 12500, left 37500The prompts run together because nothing typed the Enter key on screen. The program still read both answers correctly.
Step 2 · Ask Python yes-or-no questions
Before a program can decide anything, it needs a question with a yes-or-no answer, such as "is the balance below zero?". In Python you ask these with comparison operators. Each comparison gives back one of two values: True or False. These two values have their own type, called a Boolean, or bool for short.
Create a small practice file next to budget.py:
cat > compare.py <<'PY'
balance = 37500
print(balance < 0)
print(balance > 0)
print(balance <= 37500)
print(balance >= 40000)
print(balance == 37500)
print(balance != 37500)
PY
python3 compare.pyRead each line as a question about balance, which holds 37500:
<asks "less than?" and>asks "greater than?".<=asks "less than or equal to?" and>=asks "greater than or equal to?".==asks "equal to?". It has two equals signs. A single=is not a question: it stores a value in a variable, as inbalance = 37500.!=asks "not equal to?".
Check it worked
The output is six lines:
False
True
True
False
True
False37500 is not below zero, it is above zero, it is less than or equal to 37500, it is not 40000 or more, it equals 37500, and so it is not unequal to 37500. Change balance = 37500 to balance = -200, run python3 compare.py again and predict each line before you look.
When you have finished experimenting, delete the practice file so the folder holds only the tracker:
rm compare.pyStep 3 · Warn when the balance goes below zero
Now use a comparison to make a decision. Replace budget.py with this version, which adds an if statement between the subtraction and the summary line. The command replaces the part 2 file. To keep a copy of it, run cp budget.py budget-part2.py first:
cat > budget.py <<'PY'
budget = int(input("Monthly budget: "))
spent = int(input("Amount spent: "))
balance = budget - spent
if balance < 0:
print(f"Warning: you are {-balance} over budget.")
print("Hold off on spending until next month.")
print(f"Budget {budget}, spent {spent}, left {balance}")
PY
printf '50000\n62000\n' | python3 budget.py
printf '50000\n12500\n' | python3 budget.pyHere is what the new lines mean:
balance = budget - spentis unchanged from part 2.if balance < 0:asks the question. If the answer isTrue, Python runs the lines underneath. If it isFalse, Python skips them.- The colon at the end of the
ifline is required. It says "the block of code that belongs to this question starts on the next line". - The two
printlines are indented by four spaces. That indentation is how Python knows they belong to theif. Together they form a block. {-balance}puts a minus sign in front of the balance. When the balance is -12000,-balanceis 12000, so the warning shows how much you overspent as a positive amount.- The last
printline is not indented, so it is not part of theif. It runs every time.
Check it worked
The first run, with 62000 spent, prints the warning, the advice and then the summary:
Monthly budget: Amount spent: Warning: you are 12000 over budget.
Hold off on spending until next month.
Budget 50000, spent 62000, left -12000The second run, with 12500 spent, prints only Budget 50000, spent 12500, left 37500. The condition was False, so both indented lines were skipped.
Step 4 · See why indentation matters
In many programming languages, curly brackets mark where a block starts and ends, and indentation is only there to help people read. In Python, indentation is the block. Get it wrong and the program either will not run or does something you did not mean.
Make a broken file on purpose to see the error Python gives when a block has no indented lines:
cat > broken.py <<'PY'
balance = -100
if balance < 0:
print("Warning: over budget")
PY
python3 broken.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.
Python reads the whole file before running any of it, finds the if with nothing indented under it, and stops. Nothing is printed except the error.
A quieter mistake is indenting the wrong lines. If you had indented the summary print in budget.py as well, Python would treat it as part of the if, and the summary would only appear when you overspend. The program runs, but it is wrong.
Three habits prevent most of these problems:
- Use four spaces for each level of indentation. Most code editors insert four spaces when you press Tab in a
.pyfile. - Do not mix tabs and spaces in the same file.
- After writing an
if, read the lines below it and ask "should this line run only when the condition is true?". Indent it only if the answer is yes.
Check it worked
The output ends with an error that says something like IndentationError: expected an indented block after 'if' statement on line 2, followed by exit status 1. Python points at line 3, the print that should have been indented. Delete the practice file when you have read the error:
rm broken.pyStep 5 · Add a caution with elif and a default with else
The tracker now handles one situation. Add the other two. elif (short for "else if") asks a second question only when the first answer was False. else catches everything that is left, and has no question of its own.
Replace budget.py with the finished version for this part:
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}.")
PYLine by line, the new parts:
low_mark = budget // 10works out 10% of the budget.//divides and keeps only the whole-number part, so 50000 gives 5000 and a budget of 2505 gives 250. That keeps every amount a whole number, as in part 2.if balance < 0:is the same question as before.elif balance < low_mark:is only asked when the balance is not below zero. So any balance that reaches this line is 0 or more, and the question really means "between 0 and the low mark?".else:runs when both questions wereFalse: the balance is at or above the low mark.- Each of the three blocks is indented, and
elifandelseline up withif. The colon goes at the end of each of those lines.
Python checks the questions from top to bottom and runs only the first block whose answer is True. Exactly one of the three messages appears every time. That is also why the order matters: if you asked balance < low_mark first, an overspend of 12000 would count as less than 5000, and you would get a gentle caution instead of a warning.
The summary line from part 2 is gone, because the else branch now shows the balance. Run all three situations:
printf '50000\n12500\n' | python3 budget.py
printf '50000\n47000\n' | python3 budget.py
printf '50000\n62000\n' | python3 budget.pyCheck it worked
You see three lines, one per run, each with a different message after the prompts:
Monthly budget: Amount spent: Balance: 37500 left of 50000.
Monthly budget: Amount spent: Careful: only 3000 left, less than 10% of your budget.
Monthly budget: Amount spent: Warning: you are 12000 over budget.Run python3 budget.py once more and type amounts from your own month, such as your rent, transport or mobile data top-ups, to see which message you get.
Step 6 · Test every branch, including the edges
Each block in an if, elif, else statement is called a branch. A branch you never ran is a branch you do not know works. Programmers test each one on purpose, and pay most attention to the edges, where one branch hands over to the next. Bugs hide there, often because someone wrote < when they meant <=.
With a budget of 50000, the edges are a balance of exactly 5000, just under it, exactly 0 and just below 0. Try each one:
printf '50000\n45000\n' | python3 budget.py
printf '50000\n45001\n' | python3 budget.py
printf '50000\n50000\n' | python3 budget.py
printf '50000\n50001\n' | python3 budget.pyBefore you look at the output, predict which branch each run hits. Then write down what happened in a file called branch-tests.txt, so you can run the same cases again after later changes. You can type it in your text editor and save it in ~/budget-tracker, or create it from the terminal. The text between the two TXT markers is the file, with one row for every case you have run in this tutorial:
cat > branch-tests.txt <<'TXT'
budget spent balance branch message starts with
50000 12500 37500 else Balance:
50000 45000 5000 else Balance:
50000 45001 4999 elif Careful:
50000 47000 3000 elif Careful:
50000 50000 0 elif Careful:
50000 50001 -1 if Warning:
50000 62000 -12000 if Warning:
TXT
cat branch-tests.txtA balance of exactly 5000 shows the plain balance, because 5000 < 5000 is False. A balance of exactly 0 gets the caution, because 0 < 0 is also False, so the first question fails and the second one catches it. If you would rather be cautioned at exactly 10%, change < to <= on the elif line and run the 45000 case again.
One gap is left on purpose: if you type letters instead of a number, int() stops the program with a ValueError, as you saw in part 2. Part 8 of this series fixes that.
Check it worked
The four runs print, in order:
Monthly budget: Amount spent: Balance: 5000 left of 50000.
Monthly budget: Amount spent: Careful: only 4999 left, less than 10% of your budget.
Monthly budget: Amount spent: Careful: only 0 left, less than 10% of your budget.
Monthly budget: Amount spent: Warning: you are 1 over budget.cat branch-tests.txt prints the table: a header row and seven cases, and every branch (if, elif and else) appears in it at least twice. Keep budget.py, branch-tests.txt and the ~/budget-tracker folder: part 4 builds on the tracker.
Next steps
- Combine conditions with
and,orandnot, and learn what Python treats as true: make decisions in code with if and Boolean logic. - Part 4 lets the tracker take as many expenses as you like: keep asking for expenses until the user is done.
- Go back over how the tracker reads numbers from the keyboard: record what you spend from the keyboard with input.
Part of these paths
Related tutorials
- Record what you spend from the keyboard with inputYou will change the budget tracker so it asks for your budget and an expense when it runs, turns the typed text into numbers and prints the right balance.
- Keep asking for expenses until the user is doneYou 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.
- Make decisions in code with if, elif and boolean logicYou will build a small exam-grade and fee-discount checker in Python, using comparisons, and, or, not, truthy values and match/case, and prove every branch works with a truth table and a set of checks.
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