πŸ”€ 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! 😊