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:
  • if
  • if – elif
The else block is optional, but when present, it always runs only if no condition matches.

Basic Syntax of else

  • else does 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 → if block runs
  • If condition is False → else block 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)

  • else runs 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
  1. Write a program to check even or odd
  2. Take user input and check pass or fail
  3. Create a simple password validation using else