elif Statement
In Python, the elif (short for "else if") statement allows you to check multiple conditions in sequence. The elif statement is used after an initial if statement and before an optional else statement. The basic syntax is as follows:
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition2 is True
elif condition3:
# Code to be executed if condition3 is True
# ...
else:
# Code to be executed if none of the conditions are True
Here's a more detailed breakdown:
- The
ifstatement checks the first condition, and if it'sTrue, the corresponding block of code is executed. - If the first condition is
False, the program moves to the firstelifstatement and checks its condition. If the condition isTrue, the corresponding block of code is executed. - This process continues through each
elifstatement until aTruecondition is found or there are no moreelifstatements. - If none of the conditions in the
ifandelifstatements areTrue, the block of code under theelsestatement (if present) is executed.
Example:
x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
In this example, the program checks the first condition (x > 10). If it's True, the corresponding block of code is executed. If it's False, the program moves to the elif statement and checks the next condition (x == 10). If this condition is True, its corresponding block of code is executed. If neither condition is True, the block of code under the else statement is executed.
Example with Multiple elif Statements:
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
elif grade >= 60:
print("D")
else:
print("F")
In this example, the program checks the grade against multiple conditions and prints the corresponding letter grade based on the first condition that is True.
The elif statement is useful when you have multiple conditions to check, and you want to handle each case differently. It provides a more organized and readable way to structure your code for decision-making.