else

In Python, the else keyword specifies a block of code to be executed when a certain condition is false in control flow statements such as if, while, and for. It allows you to handle alternative scenarios in your code execution. The else block provides a way to execute code when the preceding conditional checks aren’t satisfied.

Python else Keyword Examples

Here’s a quick example demonstrating the use of the else keyword with an if statement:

Python
>>> x = 10
>>> if x > 15:
...     print("x is greater than 15")
... else:
...     print("x is 15 or less")
...
x is 15 or less

In this example, the if condition checks if x is greater than 15. Because x is 10, which isn’t greater than 15, the else block executes, printing "x is 15 or less" to the screen.

Python else Keyword Use Cases

  • Handling alternative scenarios in if statements
  • Executing code after a loop completes without encountering a break statement
  • Defining fallback logic in control flow statements

Tutorial

Conditional Statements in Python

In this step-by-step tutorial you'll learn how to work with conditional ("if") statements in Python. Master if-statements and see how to write complex decision making code in your programs.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader