Python elif Ladder
In this page:
Basic Elif Structure
An elif ladder chains several conditions together and checks them top to bottom, running only the first block whose condition is True and skipping every condition after it, even if a later one would also have matched.
Example: Basic Elif Structure
score = 75
if score >= 90:
print("A")
elif score >= 70:
print("B")
else:
print("C")
Multiple Elif Blocks
You can chain as many elif blocks as needed between an if and an optional final else, which is the standard structure for classifying a value into one of several distinct categories or ranges.
Example: Multiple Elif Blocks
temp = 15
if temp >= 30:
print("Hot")
elif temp >= 20:
print("Warm")
elif temp >= 10:
print("Cool")
else:
print("Cold")
Importance of Condition Order
Because Python stops at the first True condition, ordering matters: placing a broad condition (like score >= 60) before a narrower, more specific one (like score >= 90) means the narrower branch can never be reached.
Example: Importance of Condition Order
score = 95
if score >= 60:
print("Pass")
elif score >= 90:
print("This never runs")
Ladder with Default Fallback
A trailing else block catches every case none of the preceding conditions matched, acting as a safety net so the ladder always produces some result even for unanticipated input.
Example: Ladder with Default Fallback
day = "Funday"
if day == "Saturday":
print("Weekend")
elif day == "Sunday":
print("Weekend")
else:
print("Unknown day")
Logical Elif Checks
Each elif condition can itself combine multiple checks with and/or, letting a single ladder branch handle several related inputs together instead of requiring a separate elif for every individual combination.
Example: Logical Elif Checks
age = 25
has_ticket = True
if age < 12:
print("Child rate")
elif age >= 65 or has_ticket:
print("Discount rate")
else:
print("Full price")
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: