π¦ 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 here9. 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! π