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.