The elif (short for "else if") statement in Python allows you to check multiple conditions. It’s used when you have more than two conditions to evaluate. If the if condition is False, the program will check the elif conditions in sequence. If none of the conditions are True, the code in the else block will be executed.
Syntax:
if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition1 is False and condition2 is True
elif condition3:
# Code block to execute if condition2 is False and condition3 is True
else:
# Code block to execute if all conditions are False
The elif allows you to test more than one condition. You can have multiple elif statements after the if block.
If the first if condition is False, the program checks the elif conditions sequentially, executing the block for the first True condition.
Example 1: Basic if-elif-else Statement
x = 15
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10 but less than or equal to 20")
else:
print("x is 10 or less")
Output: x is greater than 10 but less than or equal to 20
In this example:
The first condition x > 20 is False.
The second condition x > 10 is True, so the code inside the elif block is executed.
Example 2: Using Multiple elif Conditions
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
elif x > 3:
print("x is greater than 3 but less than or equal to 5")
else:
print("x is 3 or less")
Output: x is greater than 5 but less than or equal to 10
In this case:
The first condition x > 10 is False.
The second condition x > 5 is True, so the code inside the second elif block is executed.
Example 3: Using elif with Multiple Conditions
age = 25
if age < 18:
print("You are a minor.")
elif 18 <= age <= 30:
print("You are a young adult.")
elif 31 <= age <= 60:
print("You are an adult.")
else:
print("You are a senior citizen.")
Output: You are a young adult.
Here:
The first condition age < 18 is False.
The second condition 18 <= age <= 30 is True, so the code inside this elif block is executed.
Key Points:
The elif statement is used when you need to check multiple conditions, one after another.
You can have as many elif statements as needed.
The else statement is optional, but if present, it executes when all previous conditions (if and elif) are False.
The if condition is checked first, followed by elif, and the else block (if provided) is executed only if all conditions are False.
Advantages of elif:
Readability: Helps to write clean and readable code when multiple conditions need to be tested.
Efficiency: Stops checking further conditions as soon as a True condition is found, improving performance.
Let me know if you want further examples or clarification! 😊
0 Comments