Decisions and loops
Choose with if, elif, and else
Run different blocks when conditions are true and understand indentation.
Lesson 14 of 63
Reading: about 2 min
Lesson + practice: about 13 min
Difficulty: Beginner
On this page4 sections
An if statement runs its indented block when its condition is True. Use elif for another condition and else as the fallback. Python uses indentation to define each block; use four spaces consistently.
minutes = 25
if minutes >= 60:
print("Long session")
elif minutes >= 20:
print("Standard session")
else:
print("Short session")Standard session
Order matters
Python tests branches from top to bottom and runs the first matching branch. Put more specific or higher thresholds before broader ones.
score = 92
if score >= 90:
print("Excellent")
elif score >= 50:
print("Passed")
else:
print("Try again")Excellent
Why this works
An if/elif/else chain makes one choice. Python tests conditions in order and executes only the first matching branch. Indentation shows which statements belong to a branch, so move the print() line inward by four spaces. A final else catches values that matched none of the earlier conditions.
Practice
Set temperature to 18. Print "Warm" at 25 or above, "Mild" from 15 through 24, and "Cool" below 15. Change the value to test every branch.
What happens after an elif branch matches?
Reveal answer
Python runs that branch and skips the remaining elif and else branches in the same chain.
Try another case
For score = 50 in the lesson example, which branch runs?
Check your answer
Reveal answer
The Passed branch runs because 50 is not at least 90 but is at least 50.
Your progress
Reveal the check answer or reach the end to complete this lesson.