, ,

Make Python Decide With if, elif, and else (Python for Beginners, Part 5)

Teach your program to choose. A beginner friendly guide to if, elif and else in Python 3, with runnable code, real error messages, and the expense tracker learning to flag a big spend.

Python for Beginners · Part 5 of 20

Every program you have written so far ran every line, top to bottom, no matter what. That is fine until the day your program needs to react. Charge a child less than an adult. Warn when a payment looks too large. Say good morning before noon and good evening after. For any of that, Python needs a way to choose. Here is the smallest version of choosing there is:

decide.py
age = 20
if age >= 18:
    print('You can vote')
terminal
You can vote

Change the first line to age = 15 and run it again. This time nothing prints. The if line asked a plain yes or no question, is age at least 18, and it ran the indented line only when the answer was yes. That indented line under the if is the whole idea of this part. Python looks at a condition, works out whether it is true or false, and runs a block of code only when it is true.

The short versionAn if statement runs its indented block only when a condition is true. Add else for what to do when it is false, and elif for extra questions in between. Python checks the branches from top to bottom and runs the first one that matches, then skips the rest. The two things that trip up beginners are the colon at the end of the line and the indentation of the block. Get those two right and conditions are easy.

This part builds straight on Part 4, where you read input from the user and converted it with int and float. You need Python 3 and about twenty five minutes, and nothing new to install. Copy each block into a file, run it, and your screen should match the output shown. If you are a career switcher who has never branched code before, this is the part where programs stop being calculators and start feeling like tools.

if condition age >= 18 True False run the block skip the block next line

An if statement runs the block when the condition is true and steps over it when it is false.

if: the yes or no question

The pattern is always the same. The word if, then a condition, then a colon, then an indented block on the next line. The condition is any expression that comes out either true or false. Most conditions compare two values.

Comparisons make True or False

Type this at the interactive prompt, the one you start with python on Windows or python3 on macOS and Linux, and watch what each comparison returns.

python
>>> 7 >= 7
True
>>> 3 < 2
False
>>> 10 == 10
True
>>> 10 != 9
True

Each line hands back True or False, which are real values in Python with capital letters. A condition in an if is just one of these. When it is True the block runs, when it is False the block is skipped. Here are the operators you will use every day.

OperatorMeansExampleResult
==equal to5 == 5True
!=not equal to5 != 4True
>greater than7 > 10False
<less than3 < 8True
>=greater or equal6 >= 6True
<=less or equal9 <= 4False

Notice that equal to is two equals signs, ==, not one. A single = means store a value in a variable, which is a different job. Mixing them up is so common that Python watches for it, and you will meet the exact error in a moment.

Indentation is the block

Python does not use curly braces to mark where a block starts and ends. It uses indentation, the spaces at the front of the line. Everything indented under the if belongs to it. The moment a line goes back to the left margin, you are out of the block again.

margins.py
score = 80
if score >= 60:
    print('You passed')
    print('Well done')
print('Program finished')
output
You passed
Well done
Program finished

The two indented lines only run when the score is high enough. The last line sits at the left margin, so it runs no matter what. Use four spaces for one level of indentation. It is the standard, and every Python editor will do it for you when you press Enter after the colon.

Forget to indent and Python stops you at once. Here is what that looks like, and it is worth reading rather than fearing:

broken.py
age = 20
if age >= 18:
print('You can vote')
terminal
  File 'broken.py', line 3
    print('You can vote')
    ^^^^^
IndentationError: expected an indented
block after 'if' statement on line 2

Read the last line first. It tells you plainly that Python wanted an indented block after the if on line 2 and did not find one. The fix is to put four spaces in front of the print. Error messages like this are Python doing you a favour, not scolding you. The last line names the problem, and the caret points near where it noticed.

Why this matters at workThe first real bug you fix on the job will almost certainly be a branch that took the wrong path. A refund fired when it should not have, a discount did not apply, an alert stayed quiet. Every one of those is an if with a condition that is slightly off. Reading a condition slowly and asking what is true right now, out loud, is a skill you use for your whole career. It starts with these six operators.

else and elif: the other roads

An if on its own does something or nothing. Often you want it to do one thing or another. That is what else is for. It has no condition of its own, it simply catches every case the if did not.

vote.py
age = 15
if age >= 18:
    print('You can vote')
else:
    print('Too young to vote')
output
Too young to vote

Now every age gets an answer. When you need more than two paths, elif, short for else if, lets you ask another question. You can stack as many as you like, and Python checks them from top to bottom.

grade.py
score = 72
if score >= 90:
    print('A')
elif score >= 75:
    print('B')
elif score >= 60:
    print('C')
else:
    print('Needs work')
output
C

A score of 72 is not 90 or more, so the first check fails. It is not 75 or more, so the second fails. It is 60 or more, so the third matches and prints C. Here is the part beginners miss. Once a branch matches, Python runs it and jumps past the whole rest of the chain. It does not keep checking. That is why order matters, and why you put the tighter conditions first.

if score >= 90 elif score >= 75 elif score >= 60 else print A print B print C Needs work True True True False False False

Python tries each condition in order and takes the first True path, then leaves the ladder.

A real opinionCommon beginner advice says every if should have an else so you handle every case. I disagree for a lot of everyday code. If your if only needs to act when something is true, a bare if with no else reads cleaner than an empty or pointless else branch. The other habit worth dropping early is deep nesting, an if inside an if inside an if. Three levels in, nobody can tell what is true. Reach for elif, or check the bad case first and handle it, before the code marches off the right edge of the screen.

Combining and comparing

Sometimes one condition is not enough. You want two things to be true at once, or either of two things. That is and and or, plain English words in Python.

python
age = 25
income = 40000
if age >= 21 and income > 30000:
    print('Loan check passed')
output
Loan check passed

With and both sides must be true. With or only one needs to be. There is also not, which flips a condition, so not is_member is true when the person is not a member. One neat thing Python allows that many languages do not is chaining a comparison the way you would write it by hand.

python
x = 50
if 0 < x < 100:
    print('x is between 0 and 100')
output
x is between 0 and 100

That reads exactly like maths and does what it looks like. A condition does not even have to be a comparison. Python treats some values as true and some as false on their own, which is called truthiness. Zero and empty text count as false, and almost everything else counts as true.

ValueCounts asNote
0Falsethe number zero
0.0Falsezero as a float
” (empty text)Falsenothing typed
250Trueany non zero number
‘hi’Trueany non empty text
‘0’Truetext, not the number zero

The last row is a favourite trap. The text ‘0’ is not empty, so it counts as true, even though it looks like zero. This is one more reason to convert user input with int or float before you test it, exactly as you learned in Part 4.

Now the error that catches everyone at least once. Write a single equals sign in a condition and Python refuses to run:

oops.py
score = 90
if score = 90:
    print('Top marks')
terminal
  File 'oops.py', line 2
    if score = 90:
       ^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you
meant '==' or ':=' instead of '='?

Modern Python even guesses the fix for you. A comparison needs ==. The single = is only for putting a value into a variable. Change it to if score == 90: and it runs.

Project check-in: the tracker makes a callIn Part 4 your expenses.py read a category and an amount from the user and printed them back. Now let it react to the size of the spend. Keep the top of the file as it is and add a decision underneath:
expenses.py
print('My Expense Tracker')
category = input('Category: ')
amount = float(input('Amount: '))
if amount >= 1000:
    print('Big expense, review it')
elif amount >= 100:
    print('Worth noting')
else:
    print('Small one')
print('Saved', amount, 'for', category)
terminal
My Expense Tracker
Category: Groceries
Amount: 250
Worth noting
Saved 250.0 for Groceries
An amount of 250 is not 1000 or more, so the first branch is skipped. It is 100 or more, so the second matches and prints Worth noting, then the chain ends. The tracker now has an opinion about your spending. It still handles only one expense and forgets it when the program ends. Part 6 teaches it to loop so you can enter several in a row.
if amount >= 1000 elif amount >= 100 else review it worth noting small one True True False False

The tracker sorts each amount into one of three buckets by checking the largest threshold first.

Put it together: a ticket price by age

One small program pulls in everything from this part. A cinema charges nothing under five, a child rate up to seventeen, a senior rate from sixty, and a full price for everyone else. Start by reading the age and converting it, because input from Part 4 always arrives as text.

ticket.py
age = int(input('Your age: '))

Now the decision. Order the branches from the youngest upward so each one only has to check a single edge. Whichever matches first sets the price, and the last else covers the ordinary adult.

ticket.py
age = int(input('Your age: '))
if age < 5:
    price = 0
elif age < 18:
    price = 150
elif age >= 60:
    price = 100
else:
    price = 250
print('Ticket price:', price)
terminal
Your age: 15
Ticket price: 150

An age of 15 is not under 5, but it is under 18, so the child price of 150 is set and the rest is skipped. Try 4, 70 and 30 to see the other branches fire. Now here is the common slip. Drop the int and read the age as plain text, then compare it to a number:

terminal
Your age: 15
Traceback (most recent call last):
  File 'ticket.py', line 2, in <module>
    if age < 5:
TypeError: '<' not supported between
instances of 'str' and 'int'

The last line says it cleanly. You tried to compare text with a number, and Python will not guess what you meant. The fix is the one from Part 4, wrap the input in int so the age is a real number before you compare it.

Real interview questionA screener shows you code that sets a shipping fee. It uses three separate if statements, not elif, each one setting fee. For a mid range order the final fee comes out wrong. What is happening? The strong answer: separate if statements each run on their own, so more than one can be true and a later one quietly overwrites the fee an earlier one set. Chaining them with elif makes Python stop at the first match, which is almost always what you actually want. This question checks whether you understand that elif is not just tidier, it changes the behaviour.
Try it yourselfWrite a program that asks for a temperature as a number, then prints Hot when it is 30 or more, Warm when it is 20 or more, and Cold otherwise. Convert the input with float. Match this run, typing 24 when asked.
expected terminal
Temp: 24
Warm
Show solution
weather.py
temp = float(input('Temp: '))
if temp >= 30:
    print('Hot')
elif temp >= 20:
    print('Warm')
else:
    print('Cold')
terminal
Temp: 24
Warm

Five questions about if and elif

Do I always need an else? No. Use else only when there is a real fallback action. If your code should do something in one case and nothing otherwise, a bare if is correct and clearer.

How many elif branches can I have? As many as you need. Python checks them in order and runs the first true one. If several could be true, order them so the one you want to win comes first.

Why do I keep getting an IndentationError? The block under a colon must be indented, and every line in it must line up. Use four spaces, and do not mix spaces with tabs. Most editors handle this once you press Enter after the colon.

Can I compare text, not just numbers? Yes. == checks if two strings match exactly, and it is case sensitive, so ‘Yes’ and ‘yes’ are different. Comparisons like < put strings in dictionary order, which is handy for sorting later.

What is the difference between = and ==? One equals sign stores a value in a variable. Two equals signs ask whether two values are equal. A condition always uses two. Python raises a SyntaxError if you use one by mistake.

You can now write a condition with the comparison operators, run a block only when it is true, add else and a ladder of elif branches, combine conditions with and, or and not, and read an IndentationError or a TypeError without panic.

Part 6 gives your program stamina. You will meet for and while loops, and the expense tracker will finally accept several expenses in one run instead of quitting after one. Keep expenses.py exactly as you left it here, because we build straight on top of it again. Try the temperature task before you move on, and open the solution only to check your work.

Python for Beginners · Part 5 of 20
« Previous: Part 4  |  Complete Guide  |  Next: Part 6

References

Python docs: More control flow tools (if statements)
Python docs: Comparison operators
Python docs: Truth value testing

About The Author


Discover more from Journal of Intelligent Infrastructure - By Dr Pranay Jha

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Architect’s Toolkit

About the Author

Dr. Pranay Jha is a Cloud and AI Consultant with 18+ years of experience in hybrid cloud, virtualization, and enterprise infrastructure transformation. He specializes in VMware technologies, multi-cloud strategy, and Generative AI solutions. He holds a PhD in Computer Applications with research focused on Cloud and AI, has published multiple research papers, and has been a VMware vExpert since 2016 and a VMUG Community Leader.

Discover more from Journal of Intelligent Infrastructure - By Dr Pranay Jha

Subscribe now to keep reading and get access to the full archive.

Continue reading