π Python Elif Statement β Handling Multiple Conditions
Introduction π
The elif (short for βelse ifβ) statement allows you to check **multiple conditions one by one**. It is used when your program needs to choose between more than two possible paths.
Note
π‘ Only the **first True** condition will execute β all others are skipped.
1. Basic Elif Structure π§±
basic_elif.py
x = 10
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("Less than 10")Python evaluates conditions from top to bottom. Once a condition becomes True, remaining conditions are ignored.
2. Using Multiple Elif Conditions β
multiple_elif.py
marks = 85
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")Note
βοΈ Elif helps avoid writing many nested if statements.
3. Elif With Logical Operators π
elif_logical.py
age = 25
if age < 13:
print("Child")
elif age >= 13 and age < 20:
print("Teenager")
elif age >= 20 and age < 60:
print("Adult")
else:
print("Senior")4. Elif With User Input β¨οΈ
elif_input.py
day = input("Enter day: ").lower()
if day == "monday":
print("Start of the week!")
elif day == "friday":
print("Almost weekend!")
elif day == "sunday":
print("Weekend π")
else:
print("Regular day")5. Elif With String Conditions π€
elif_strings.py
fruit = "banana"
if fruit == "apple":
print("It's an apple")
elif fruit == "banana":
print("It's a banana")
elif fruit == "mango":
print("It's a mango")
else:
print("Unknown fruit")6. Avoiding Deep Nesting With Elif π§
avoid_nesting.py
# Without elif (bad practice)
x = 20
if x < 0:
print("Negative")
else:
if x == 0:
print("Zero")
else:
print("Positive")
# With elif (better)
if x < 0:
print("Negative")
elif x == 0:
print("Zero")
else:
print("Positive")Note
βοΈ Elif improves readability and simplifies complex conditions.
7. Elif In Real-World Decision Making π
real_world_example.py
temp = int(input("Enter temperature: "))
if temp >= 40:
print("π₯ Very Hot")
elif temp >= 30:
print("βοΈ Hot")
elif temp >= 20:
print("π€οΈ Normal")
elif temp >= 10:
print("βοΈ Cold")
else:
print("β Very Cold")8. Important Rules of Elif β οΈ
- Elif must follow an if statement.
- You can use multiple elif statements.
- Only one block will execute (the first True condition).
- else is optional.
Conclusion π
>>βElif lets your program choose the best path β smart, clean, and powerful.β β¨
You now understand the elif statement in Python. Want the next tutorial on If-Else, Nested If, Conditional Expressions, or Loops? Just tell me! π