Python if, elif and else: your code makes its first damn decision
Updated · every example run on Python 3.9 to 3.15
Every program so far has been a train on one track: line 1, line 2, line 3, the end, no matter what. Real programs look at something first and then decide. Is the balance negative? Is the cat too heavy? Is it 2 a.m., and should you really be learning Python right now? (Yes. Keep going.)
That decision is if. It's one word, a colon and a few spaces, and it's where most beginners meet their first IndentationError. You'll meet yours on purpose, near the end, where it can't hurt anyone.
if: run this only when it's true
An if line has a condition and ends with a colon. The lines under it are indented, four spaces each, and they run only when the condition is true:
balance = -40
if balance < 0:
print("You are overdrawn.")
print("Put the credit card down.")
print("Balance:", balance)You are overdrawn.
Put the credit card down.
Balance: -40The indented lines are the if's block. The first line back at the left edge is outside it, so it runs either way. Change balance to 250 and run it again: only the last line prints.
Python has no curly braces for this. The indentation is the syntax, which is why it's so fucking fussy about it. Most code editors put in four spaces when you press Tab in a .py file, and four is the convention everybody uses.
else and elif: the other roads
else catches everything the if didn't. elif is short for "else if" and adds another test in between. You can stack as many as you like:
battery = 14
if battery > 50:
print("You're fine. Go outside.")
elif battery > 20:
print("Find a charger at some point.")
elif battery > 5:
print("Low battery. Panic quietly.")
else:
print("Your phone is about to die. Say goodbye to the podcast.")
print("Checked at", battery, "percent")Low battery. Panic quietly.
Checked at 14 percentPython tries the tests from the top and runs the first block whose test is true, then skips every other branch. 14 isn't above 50 or 20, it is above 5, done. else has no condition: it's the "none of the above" bin, and it goes last.
Order matters like hell here. Put battery > 5 first and a phone at 100% lands in the panic branch, because 100 is, technically, above 5. Also, the word is elif. Writing else if on one line is a syntax error, and yes, everybody does it once.
Comparisons are just True or False
The condition is usually a comparison, and a comparison is an expression like any other: it produces a bool, True or False.
print(5 > 3)
print(5 == 5.0)
print("cat" == "Cat")
print(10 != 10)
print(3 <= 3)
print("Zebra" < "apple")
cat_weight = 6.2
print(4 <= cat_weight <= 6)
print(type(cat_weight > 6))True
True
False
False
True
True
False
<class 'bool'>The six operators: == equal, != not equal, <, >, <=, >=. An int and a float compare by value, so 5 == 5.0 holds. Strings compare exactly, case included.
They also compare character by character, by each character's Unicode number, and the capitals A to Z all come before the lowercase a to z. That's why "Zebra" comes before "apple". Computers: still bad at the alphabet.
4 <= cat_weight <= 6 is a chained comparison and reads like math class: both halves have to hold. At 6.2 kilos the second half fails. The cat disputes this.
= is not ==
One equals sign puts a value into a variable. Two ask a question. Use one where you meant two:
print("Weighing the cat...")
cat_weight = 6
if cat_weight = 6:
print("Perfect cat.") File "/home/me/project/main.py", line 3
if cat_weight = 6:
^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?| Python | Prints |
|---|---|
| 3.9 | SyntaxError: invalid syntax |
| 3.10–3.15 | SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
Notice what didn't happen: "Weighing the cat..." never printed. A syntax error stops Python before it runs a single line, because it reads the whole file first. Python 3.9 just calls it invalid syntax. From 3.10 on it guesses the mistake and asks whether you meant == (or :=, the "walrus" operator, which this course will happily never need). More on this error at SyntaxError: invalid syntax.
and, or, not
Glue conditions together. and wants both sides true, or wants at least one, and not flips a bool around:
hungry = True
money = 8
pizza_price = 12
fridge_empty = True
if hungry and money >= pizza_price:
print("Order the pizza.")
else:
print("Pizza is not happening.")
if fridge_empty or money < 5:
print("Dinner is toast. Literally.")
if not fridge_empty:
print("Cook something.")
else:
print("Go shopping first.")Pizza is not happening.
Dinner is toast. Literally.
Go shopping first.Hungry, yes, but 8 is less than 12, so and fails: no pizza. The fridge is empty, so or is satisfied by its first half alone.
Python also stops as soon as it knows the answer: and quits at the first false part and or at the first true one, so the second half sometimes never runs. And when you mix them, not goes first, then and, then or. Nobody remembers that at 2 a.m., so use parentheses: (hungry or bored) and money > 0.
Truthy and falsy
An if doesn't strictly need a comparison. Hand it any value and it asks: do you count as true?
name = ""
cats = 0
if name:
print("Hello,", name)
else:
print("No name given.")
if cats:
print("You have cats.")
else:
print("No cats. The house is just a building.")
print(bool(""), bool("Ada"), bool(0), bool(-3))
print(bool(0.0), bool(None), bool("False"))No name given.
No cats. The house is just a building.
False True False True
False False Truebool() shows the verdict. The falsy values are False, None, zero of any kind (0, 0.0) and empty things: the empty string now, the empty list next lesson. Everything else is truthy. Including -3. Including the string "False", which is five letters long and therefore, as far as Python cares, true as hell.
So if name: means "if name isn't empty". You'll see it everywhere.
The colon and the indent
The colon says "a block starts here". The indent says which lines are in it. Leave out the indent:
milk_left = 0
if milk_left == 0:
print("Buy milk.") File "/home/me/project/main.py", line 3
print("Buy milk.")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 2| Python | Prints |
|---|---|
| 3.9 | IndentationError: expected an indented block |
| 3.10–3.15 | IndentationError: expected an indented block after 'if' statement on line 2 |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
Python 3.9 says it expected an indented block. From 3.10 on it also names the statement that wanted one and its line, which saves you a minute of squinting. The fix is four spaces; IndentationError: expected an indented block has the rest.
Leave out the colon instead and you get SyntaxError: expected ':' from 3.10 on, plain invalid syntax on 3.9. And don't mix tabs and spaces in one block: Python won't guess how wide your tab is meant to be, and raises a TabError instead.
Try it yourself
Write a thermostat. Put a number in temperature at the top of the file and print "Stay inside, it's an oven." above 30, "T-shirt weather." from 18 to 30, "Bring a jacket." from 5 up to 18, and "Absolutely not." below 5. Try it with 31, 18, 5 and -2.
Show the answer
temperature = 18
if temperature > 30:
print("Stay inside, it's an oven.")
elif temperature >= 18:
print("T-shirt weather.")
elif temperature >= 5:
print("Bring a jacket.")
else:
print("Absolutely not.")
Each elif runs only when every test above it failed, so temperature >= 18 already knows the number is 30 or less. No need to write 18 <= temperature <= 30.
Questions
What is the difference between = and == in Python?
= assigns: it puts a value into a variable. == compares: it asks whether two values are equal and answers True or False. An if needs the question, so it takes ==.
How many spaces should I indent in Python?
Four per level. Python itself only needs every line of a block indented the same way, but four spaces is the convention in PEP 8, Python's style guide, and most code editors do it for you.
Does Python have a switch statement?
Not one called switch. A chain of elif does the job, and since Python 3.10 there's also a match statement that compares a value against patterns. It doesn't exist in 3.9, and nothing in this course needs it.
How do I use input() with if in Python?
input() always returns a string, so convert it before comparing: age = int(input("How old are you? ")), then if age >= 18:. Use < or >= on the raw string and a number and Python raises a TypeError, because it won't guess whether "17" is text or a number. == is sneakier: "17" == 17 raises nothing and is just False, every time.
Sources
- More control flow tools: if statements, Python documentation
- Comparisons, Python documentation
- Boolean operations, Python documentation
- Truth value testing, Python documentation
- The match statement, Python documentation
- PEP 8: indentation, Python Enhancement Proposals
Read on November 11, 2026.