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:
>>> 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
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python for Loops: The Pythonic Way (Tutorial)
- Python while Loops: Repeating Tasks Conditionally (Tutorial)
- Conditional Statements in Python (if/elif/else) (Course)
- Python Conditional Statements (Quiz)
- For Loops in Python (Definite Iteration) (Course)
- Python for Loops: The Pythonic Way (Quiz)
- Mastering While Loops (Course)
- Python while Loops: Repeating Tasks Conditionally (Quiz)