Python & data · Lesson 05
Decisions with conditionals
Compare values and choose a branch with if, elif, and else.
- Write comparisons
- Choose between branches
- Combine conditions and read indentation
Helpful background: Know how to assign variables and work with numbers.
Compare values
Comparisons such as ==, !=, <, and >= produce boolean values. Use == to compare two values; a single = is used for assignment.
For numbers, the usual order comparisons apply. For strings, comparisons are case-sensitive.
temperature = 24
print(temperature >= 20) # True
print(temperature == 20) # FalseChoose a branch
An if statement runs its indented block when the condition is true. elif checks another condition only if the previous conditions were false; else handles the remaining case.
Python uses indentation to define a block. Use a consistent four spaces for each level.
score = 72
if score >= 80:
print("Excellent")
elif score >= 60:
print("Passed")
else:
print("Keep practicing")Combine conditions
Use and when both conditions must be true, or when either is enough, and not to invert a condition. Parentheses can make a longer condition easier to understand.
Order matters: Python evaluates conditions from left to right and may stop once the result is known.
age = 18
has_ticket = True
if age >= 18 and has_ticket:
print("Entry allowed")Test the boundaries
Try values exactly on either side of a boundary. If the rule is at least 18, test 17, 18, and 19. These examples help reveal an accidental > where >= was intended.
Which operator checks whether two values are equal?
Your turn
Print "warm" when temperature is at least 20; otherwise print "cool".
temperature = 20 if temperature >= 20: print("warm") else: print("cool")
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited