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:
age = 20
if age >= 18:
print('You can vote')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.
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.
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.
>>> 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.
| Operator | Means | Example | Result |
|---|---|---|---|
| == | equal to | 5 == 5 | True |
| != | not equal to | 5 != 4 | True |
| > | greater than | 7 > 10 | False |
| < | less than | 3 < 8 | True |
| >= | greater or equal | 6 >= 6 | True |
| <= | less or equal | 9 <= 4 | False |
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.
score = 80
if score >= 60:
print('You passed')
print('Well done')
print('Program finished')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:
age = 20
if age >= 18:
print('You can vote') File 'broken.py', line 3
print('You can vote')
^^^^^
IndentationError: expected an indented
block after 'if' statement on line 2Read 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.
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.
age = 15
if age >= 18:
print('You can vote')
else:
print('Too young to vote')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.
score = 72
if score >= 90:
print('A')
elif score >= 75:
print('B')
elif score >= 60:
print('C')
else:
print('Needs work')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.
Python tries each condition in order and takes the first True path, then leaves the ladder.
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.
age = 25
income = 40000
if age >= 21 and income > 30000:
print('Loan check passed')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.
x = 50
if 0 < x < 100:
print('x is between 0 and 100')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.
| Value | Counts as | Note |
|---|---|---|
| 0 | False | the number zero |
| 0.0 | False | zero as a float |
| ” (empty text) | False | nothing typed |
| 250 | True | any non zero number |
| ‘hi’ | True | any non empty text |
| ‘0’ | True | text, 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:
score = 90
if score = 90:
print('Top marks') 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.
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)My Expense Tracker Category: Groceries Amount: 250 Worth noting Saved 250.0 for Groceries
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.
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.
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)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:
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.
Temp: 24 Warm
Show solution
temp = float(input('Temp: '))
if temp >= 30:
print('Hot')
elif temp >= 20:
print('Warm')
else:
print('Cold')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.
References
Python docs: More control flow tools (if statements)
Python docs: Comparison operators
Python docs: Truth value testing


DrJha