Python Tutorials · Python If...Else

Python Else

Learn all about Python Else in this comprehensive tutorial.

5 min read beginner
  • The else keyword catches anything which isn't caught by the preceding conditions.
  • You can also have an else without the elif:
  • The else statement provides a default action when none of the previous conditions are true.
  • You can combine if, elif, and else to create a comprehensive decision-making structure.
  • The else statement acts as a fallback that executes when none of the preceding conditions are true.

The Else Keyword

The else keyword catches anything which isn't caught by the preceding conditions.

The else statement is executed when the if condition (and any elif conditions) evaluate to False.

python

In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b".

Else Without Elif

You can also have an else without the elif:

python

This creates a simple two-way choice: if the condition is true, execute one block; otherwise, execute the else block.

How Else Works

The else statement provides a default action when none of the previous conditions are true. Think of it as a "catch-all" for any scenario not covered by your if and elif statements.

Note: Note: The else statement must come last. You cannot have an elif after an else.
python

Complete If-Elif-Else Chain

You can combine if, elif, and else to create a comprehensive decision-making structure.

python

Else as Fallback

The else statement acts as a fallback that executes when none of the preceding conditions are true. This makes it useful for error handling, validation, and providing default values.

python

Module quiz

2 questions
1

Which of the following is true about Python Else?

2

What is the most common pitfall when working with Python Else?

Answer all questions to submit.