If-Elif-Else Statement in Python

What is an If-Elif-Else Statement?

The if-elif-else statement allows you to check multiple conditions sequentially. Python executes the first condition that is true, skipping the rest.

Syntax

if condition1:
    # code block 1
elif condition2:
    # code block 2
else:
    # code block if all conditions fail

Example

marks = 75
if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 60:
    print("Grade C")
else:
    print("Fail")

How It Works

Python checks each condition from top to bottom. Once a true condition is found, the corresponding block executes, and the rest are skipped.

Additional Examples

# Example 1
num = 0
if num > 0:
    print("Positive")
elif num == 0:
    print("Zero")
else:
    print("Negative")

# Example 2
day = "Tuesday"
if day == "Monday":
    print("Start of the week")
elif day == "Friday":
    print("Almost weekend")
elif day == "Sunday":
    print("Weekend!")
else:
    print("Midweek day")

# Example 3
score = 85
if score >= 90:
    print("Excellent")
elif score >= 80:
    print("Very Good")
elif score >= 70:
    print("Good")
else:
    print("Needs Improvement")

# Example 4
temperature = 15
if temperature > 30:
    print("Hot")
elif temperature > 20:
    print("Warm")
elif temperature > 10:
    print("Cool")
else:
    print("Cold")

# Example 5
color = "green"
if color == "red":
    print("Stop")
elif color == "yellow":
    print("Get Ready")
elif color == "green":
    print("Go")
else:
    print("Invalid color")