The else condition is used to define what should happen when an if condition is not satisfied. While if handles the case when a condition is true, else handles the opposite situation. It ensures that a program always has a clear outcome, no matter how the condition turns out.
When Python reaches an if–else statement, it first checks the condition.
- If the condition is
True, theifblock runs. - If the condition is
False, theelseblock runs.
Example:
1age = 15
2
3if age >= 18:
4 print("You are eligible to vote")
5else:
6 print("You are not eligible to vote")Here, Python checks the value of age. Because it is less than 18, the else block executes.
Real-Life Meaning
Think about entering a password.
- If the password is correct, you get access.
- Otherwise, you are denied.
That “otherwise” is handled by the else block.
Nested else in Python
A nested else appears when an if–else structure is placed inside another if or else. This allows Python to deal with multiple levels of decision-making, where each result leads to another choice.
Example:
1age = 20
2has_ticket = False
3
4if age >= 18:
5 if has_ticket:
6 print("You can enter the theater")
7 else:
8 print("Buy a ticket first")
9else:
10 print("You are too young to enter")Here, Python follows this logic:
- Check if the person is 18 or older.
- If yes, check if they have a ticket.
- If not 18, deny entry directly.
Why Nested else Is Important
Real systems always need fallback rules. A login system needs to know what to do if a password is wrong. A payment system needs to know what to do if a balance is too low. Nested else statements let programs handle these alternate paths cleanly.
Conclusion
The else condition completes a decision. It tells Python what to do when things do not go as expected. Nested else statements extend this idea, allowing software to handle complex, multi-step outcomes in a controlled and logical way.
