An if statement lets your program make decisions: run this code only if something is true. Add elif and else and you can choose between several paths.
IF ON ITS OWN
hp = 0
if hp == 0:
print("Game over")Game over
The condition after if is checked. If it is True, the indented block runs. If it is False, Python skips it.
IF / ELSE: ONE OR THE OTHER
age = 15
if age >= 18:
print("Welcome!")
else:
print("Ask a parent first")Ask a parent first
ELIF: MORE THAN TWO CHOICES
Python checks the conditions from top to bottom and runs only the first one that is true.
score = 72
if score >= 90:
print("A")
elif score >= 70:
print("B")
elif score >= 50:
print("C")
else:
print("Try again")B
>= 50, but Python never gets there: it stopped at the first true branch.COMPARISON OPERATORS
==equal,!=not equal<><=>=less / greater (or equal)inis it inside?"a" in "snake"isTrue
AND, OR, NOT
coins = 12
has_key = True
if coins >= 10 and has_key:
print("Door opens")
if not has_key or coins < 5:
print("Stuck")Door opens
and needs both sides true, or needs at least one, not flips the answer.
x = 5
if x > 3:
print("big")
elif x > 1:
print("medium")
else:
print("small")x > 3 and x > 1 are true, but only the first true branch runs. One if/elif chain prints at most one thing.TRUTHY AND FALSY
You don't always need a comparison. Empty things count as False: 0, "", [], None. Almost everything else counts as True.
name = ""
if name:
print("Hi", name)
else:
print("Please type your name")Please type your name
COMMON BEGINNER MISTAKES
= instead of ==. = stores a value, == compares. if x = 5: is a SyntaxError.if, elif or else.if when you meant elif. Separate ifs are all checked, so several of them can run."Yes" == "yes" is False. Use answer.lower() == "yes".temp = 25
if temp > 20:
print("warm")
if temp > 10:
print("not cold")if statements, not an elif chain, so Python checks both. Both are true, so both lines print.PRACTICE IT, DON'T JUST READ IT
Loop Lagoon in Snekcade turns this into quick swipes: predict the output, fix the condition, then write your own. It is one of the two free worlds.
PLAY LOOP LAGOON ▸FAQ
What is the difference between if and elif in Python?
Every if starts a new check. An elif belongs to the if above it and is only checked when everything before it was false, so in one if/elif/else chain at most one block runs.
Do I always need an else?
No. else is optional. Use it when you want something to happen when none of the conditions were true.
Why does Python say SyntaxError on my if statement?
Usually a missing colon at the end of the if line, or using = (assignment) instead of == (comparison).