Lesson 5 of 34 · Fundamentals
Python If, Elif and Else Statements
Programs become interesting when they can make decisions: open the door if the player has the key, show a warning if the password is too short. In Python you make decisions with if, elif and else.
Comparisons produce booleans
A comparison asks a yes/no question and answers with True or False:
| Operator | Meaning | Example |
|---|---|---|
== |
equal to | level == 3 |
!= |
not equal to | name != "Bo" |
<, > |
less / greater than | hp < 10 |
<=, >= |
less / greater or equal | gold >= 100 |
Python also lets you chain comparisons the way you would in math: 0 <= score <= 100.
The if statement
health = 25
if health < 30:
print("Warning: low health!")
print("Turn over.")
The condition ends with a colon, and the code that belongs to it is indented (four spaces is the standard). Indentation isn't just style in Python — it defines which lines are inside the if. The last print isn't indented, so it always runs.
else and elif
else runs when the condition is false. elif ("else if") adds more conditions to check, in order:
temperature = 18
if temperature >= 30:
print("Hot")
elif temperature >= 15:
print("Pleasant")
elif temperature >= 0:
print("Chilly")
else:
print("Freezing")
Python checks the branches from top to bottom and runs only the first one whose condition is true. Here 18 >= 30 is false and 18 >= 15 is true, so it prints Pleasant and skips the rest.
Combining conditions: and, or, not
has_key = True
is_night = False
if has_key and not is_night:
print("You open the gate.")
if is_night or not has_key:
print("The gate stays shut.")
a and bis true only if both are true.a or bis true if at least one is true.not aflipsTruetoFalseand back.
Truthy and falsy values
if accepts any value, not only booleans. Python treats False, None, 0, 0.0, the empty string "" and empty collections as falsy; everything else is truthy:
name = ""
if not name:
print("Please enter a name.")
Conditional expressions
For a simple either/or value, Python has a one-line form:
status = "alive" if health > 0 else "defeated"
Common mistakes
=instead of==:if level = 3:is aSyntaxError. One=assigns; two compare.- Forgetting the colon or the indentation after
if,eliforelse. if x == 1 or 2:is always true, because2on its own is truthy. Writeif x == 1 or x == 2:— orif x in (1, 2):.- Wrong branch order: checking
score >= 60beforescore >= 90means a score of 95 matches the first branch and never reaches the second. Put the most specific conditions first.
Assignment
Write two functions:
grade(score)returns a letter grade for a test score:"A"for 90–100,"B"for 80–89,"C"for 70–79,"D"for 60–69,"F"for 0–59"Invalid"for scores below 0 or above 100
can_cast(mana, cost, is_silenced)returnsTrueif the wizard has at leastcostmana and is not silenced, otherwiseFalse.
grade(95) # "A"
grade(60) # "D"
grade(101) # "Invalid"
can_cast(20, 15, False) # True
can_cast(50, 15, True) # FalseIf/else and conditions in other languages
- JavaScript if/else Statements and Comparison Operators · JavaScript
- Go if/else and switch Statements · Go
- Java if/else and switch Statements · Java
- C# if/else, switch and Switch Expressions · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .