elif
In Python, the elif keyword defines a branch in a conditional statement to check alternative expressions for truth value. It stands for else if and allows you to chain several conditions together in a readable way. By using elif, you can avoid excessive nesting of if statements.
Python elif Keyword Examples
Here’s an example to illustrate how you can use the elif keyword in Python:
>>> number = 15
>>> if number < 10:
... print("Less than 10")
... elif number < 20:
... print("Between 10 and 20")
... else:
... print("20 or more")
...
Between 10 and 20
In this example, you check the variable number against multiple values. The if statement checks if number is less than 10. Because number is 15, this condition is false, so the program moves to the elif block, which checks whether number is less than 20. This condition is true, so "Between 10 and 20" is printed to the console. If neither the if nor the elif condition were true, the else block would execute.
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:
- Structural Pattern Matching in Python (Tutorial)
- Python Keywords: An Introduction (Tutorial)
- Conditional Statements in Python (if/elif/else) (Course)
- Python Conditional Statements (Quiz)
- Using Structural Pattern Matching in Python (Course)
- Structural Pattern Matching (Quiz)
- Exploring Keywords in Python (Course)
- Python Keywords: An Introduction (Quiz)