Python else Statement
What Is the else Keyword?
The
else keyword
in Python defines a default block of code that runs when all preceding
conditions fail.
If none of the
if or
elif
expressions evaluate to
True, Python
automatically executes the
else block.
Basic Usage of else
Example: Comparing Two Values
Explanation:
-
The
ifcondition fails -
The
elifcondition also fails -
Python executes the
elseblock as the final option
Using else Without elif
An
else
statement can directly follow an
if when you
only need a yes-or-no decision.
Example: Simple Condition Check
Explanation:
- If the condition is true, the first block runs
-
Otherwise, the
elseblock executes
How the else Statement Works
- Python evaluates conditions from top to bottom
-
If no condition matches,
elseis triggered -
elsemust always be placed at the end -
No
elifcan appear afterelse
Example: Even or Odd Number Check
Why this works: The condition checks for odd numbers. The
else handles
the remaining even cases automatically.
Complete if–elif–else Structure
Combining if,
elif, and
else allows
you to handle multiple exclusive outcomes in a clean and readable way.
Example: Weather Status Program
else as a Fallback Mechanism
The
else block is
commonly used as a safety net for:
- Input validation
- Error handling
- Default responses
