What is if-elif-else?
In Python, the if-elif-else statement is a multi-way decision-making structure. It is used when you want to check multiple conditions and execute only one block of code based on which condition is True.
It is more readable than using multiple if statements separately.
It helps us control the flow of program execution based on different conditions.
Syntax:
if condition1:
# code block 1
elif condition2:
# code block 2
elif condition3:
# code block 3
else:
# default block if none of the above are true
Real-Life Example
Suppose a person checks weather and decides what to wear:
weather = "rainy"
if weather == "sunny":
print("Wear sunglasses.")
elif weather == "rainy":
print("Take an umbrella.")
elif weather == "snowy":
print("Wear a coat and boots.")
else:
print("Have a great day!")
Output:
Take an umbrella.
Explanation:
- Here, the value of
weather
is "rainy", so the second condition is True. - Only the block under
elif weather == "rainy"
is executed. - Other conditions are skipped.
Flow of execution
As soon as a condition is True → that block executes, and others are skipped.
Note: You can have multiple elif
blocks, but only one
if
and
one optional else
block.
Key Points
- Use
if
for the first condition. - Use
elif
for additional conditions. - Use
else
as the final default option. - Only one block is executed — the first one where condition is True.
Summary
- if-elif-else is used to handle multiple decision paths.
- Checks conditions in order until one is true.
- Helps in creating clear, readable decision-making logic.