Python elif Ladder
In this page:
if condition1:
# block 1
elif condition2:
# block 2
else:
# default block
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: # only checked because the first condition was False
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: # this is the first condition that matches
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: # this broad condition matches first
print("Pass")
elif score >= 90:
print("This never runs") # unreachable because the elif above it already caught this
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") # fallback for any day not matched above
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: # combines two checks in one elif
print("Discount rate")
else:
print("Full price")
- Ordering conditions from general to specific, e.g.
score >= 60beforescore >= 90, so the later branch can never run. - Writing
else ifinstead ofelif, which is aSyntaxError. - Using separate
ifstatements instead ofelif, so several branches run when only one should.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: