Python if elif and else are control flow statements that allow you to create multiple selection in your code.
They are used to make decisions based on whether certain conditions, not only single condition is true or false.
The elif statement in Python if elif and else
- If the immediate if statement’s condition is false, the elif statement is used to check an extra condition. At that time elif statement have to be used.
- You can have multiple elif statements to check multiple conditions sequentially in the single code. The first elif block with a true condition will be executed, and the rest will be skipped.
Syntax
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
elif condition3:
# Code to execute if condition3 is true
else:
# Code to execute if none of the conditions is true
Example 1
Ask user to enter weight. You should print the status as follows
weight greater than 90kg, status=“You’re Not Good. You’re Obese”
weight less than 25kg, status= “Underweight”
others, status = “Good, You’re Normal”
Explanation 1:
- Here Question has 3 conditions
- weight>90
- weight<25 and
- other, this means weight between 25 to 90.
- So that we have to write 2 conditions and else statement.
- Notice weight condition has no greater than or equal part.
- Please be remember, you can’t put kg with the weight. if so it will become alpha numeric. Then can’t compare numeric with alpha numeric
Answer 1
weight=float(input(“Enter Weight:”))
if weight>90:
print(“You’re Not Good. You’re Obese”)
elif weight<25:
print(“Underweight”)
else:
print(“Good, You’re Normal”)
Output 1
Enter Weight:24
Underweight
Enter Weight:90
Good, You’re Normal
Enter Weight:91
You’re Not Good. You’re Obese