← Back to Python Course | Chapter 3: Control Flow | Lesson 3 of 10

Python elif Ladder

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

python
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

python
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

python
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

python
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

python
age = 25
has_ticket = True
if age < 12:
    print("Child rate")
elif age >= 65 or has_ticket:
    print("Discount rate")
else:
    print("Full price")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.