How to Use elif in Python: Simple Guide with Examples
In Python,
elif is used to check multiple conditions after an initial if statement. It stands for "else if" and lets you run different code blocks depending on which condition is true, without writing many nested if statements.Syntax
The elif statement comes after an if and before an optional else. It lets you test another condition if the previous if or elif was false.
- if condition: Runs if this condition is true.
- elif condition: Runs if previous conditions were false and this one is true.
- else: Runs if all above conditions are false.
python
if condition1: # code block 1 elif condition2: # code block 2 else: # code block 3
Example
This example shows how elif helps choose one message based on a number's value.
python
number = 15 if number < 10: print("Number is less than 10") elif number < 20: print("Number is between 10 and 19") else: print("Number is 20 or more")
Output
Number is between 10 and 19
Common Pitfalls
People often forget that elif must come after an if and before else. Also, using multiple separate if statements instead of elif can cause all conditions to be checked, which may lead to unexpected results.
Wrong way (multiple if):
python
number = 15 if number < 10: print("Less than 10") if number < 20: print("Less than 20") else: print("20 or more") # Right way using elif: if number < 10: print("Less than 10") elif number < 20: print("Less than 20") else: print("20 or more")
Output
Less than 10
Less than 20
Quick Reference
| Keyword | Purpose |
|---|---|
| if | Check the first condition |
| elif | Check additional conditions if previous ones are false |
| else | Run code if all previous conditions are false |
Key Takeaways
Use
elif to check multiple conditions clearly without nesting.elif must follow an if and come before else.Avoid using separate
if statements when elif is needed to prevent multiple blocks running.elif helps your code run only one matching block among many conditions.