Else Statement
3 min read ·
The
else statement is used to execute a block of code when all previous conditions are False.It works together with:
ifif – elif
The
else block is optional, but when present, it always runs only if no condition matches.Basic Syntax of else
elsedoes not have a condition- Colon
:is mandatory - Indentation defines the block
Note
An else block can appear only once in an if structure and must be at the end.
Simple Example of if – else
- If condition is True →
ifblock runs - If condition is False →
elseblock runs
else with Mathematical Condition
else with User Input
else with String Comparison
Caution
String comparison in Python is case-sensitive.
else with Boolean Values
else with Multiple Conditions (if – elif – else)
elseruns only if all conditions above fail
Nested else
else Without Indentation (Wrong)
Stop
Incorrect indentation causes an IndentationError.
Real World Example – Login System
Real World Scenario
Simple login validation using else
Logical Flow of else
- Python checks condition
- If False, it directly jumps to else
Common Mistakes with else
Using Condition with else ❌
Placing else Before elif ❌
Caution
else must always come after all elif blocks.
Exercise
Practice Task
- Write a program to check even or odd
- Take user input and check pass or fail
- Create a simple password validation using else