🚦 Python Else Statement β€” Handling the "Otherwise" Condition

Introduction 🌟

The else statement is used to specify a block of code that will run when all previous if or elif conditions are False. It acts as the **fallback** or **default** case in decision-making.

Note

πŸ’‘ The else block does NOT have a condition β€” it runs automatically when no other condition is True.

1. Basic Else Statement βœ”οΈ

basic_else.py

age = 16

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

The else block runs only because the if condition is False.

2. Else With Elif Ladder πŸ”—

elif_else.py

marks = 45

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

Note

βœ”οΈ The else block handles all cases not covered by if or elif.

3. Else With User Input ⌨️

else_input.py

name = input("Enter your name: ")

if name == "Sathish":
    print("Welcome, Sathish!")
else:
    print("Unknown user")

4. Else With Logical Conditions 🧠

else_logic.py

num = 12

if num % 2 == 0:
    print("Even number")
else:
    print("Odd number")

5. Else With Membership Operators πŸ”Ž

else_membership.py

fruits = ["apple", "banana", "mango"]

if "orange" in fruits:
    print("Orange is available")
else:
    print("Orange not found")

6. Else in Nested If Statements πŸͺœ

nested_else.py

age = 25

if age >= 18:
    print("Adult")

    if age >= 21:
        print("Eligible for license")
    else:
        print("Not eligible for license yet")
else:
    print("Minor")

7. Else With Multiple Conditions 🌐

complex_else.py

x = 5
y = 10

if x > y:
    print("x is greater")
elif x == y:
    print("x and y are equal")
else:
    print("x is smaller")

8. Else Is Optional βœ”οΈ

You can write if statements without an else.
But when used, else always runs as the default block.

optional_else.py

temp = 30

if temp > 35:
    print("Too hot")
# No else here

9. Real-World Example 🌍

real_world_example.py

username = input("Enter username: ")
password = input("Enter password: ")

if username == "admin" and password == "1234":
    print("Login successful")
else:
    print("Invalid credentials")

Conclusion πŸŽ‰

>>β€œThe else block ensures your code always has a final answer β€” no loose ends.” ✨

You now understand how the else statement works in Python! Want the next topic? Try Nested If, Conditional Expressions (Ternary), Loops, or Control Flow. Just tell me! 😊