Python else Statement
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python else Statement

Kishore V

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

x is larger than y

Explanation:

  • The if condition fails
  • The elif condition also fails
  • Python executes the else block 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

Access denied

Explanation:

  • If the condition is true, the first block runs
  • Otherwise, the else block executes

How the else Statement Works

  • Python evaluates conditions from top to bottom
  • If no condition matches, else is triggered
  • else must always be placed at the end
  • No elif can appear after else

Example: Even or Odd Number Check

Even number

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

Mild weather

else as a Fallback Mechanism

The else block is commonly used as a safety net for:

  • Input validation
  • Error handling
  • Default responses

Example: User Input Validation

Invalid input: Email is required
Our website uses cookies to enhance your experience. Learn More
Accept !