Which statement is used to check multiple conditions in Python?
a) while
b) for
c) elif
d) break
Answer:
c) elif
Explanation:
The elif
statement in Python, short for “else if,” is used to check multiple conditions in sequence. If the condition for if
is false, the program checks the condition for elif
. If the elif
condition is true, the corresponding block of code is executed.
x = 10
if x < 5:
print("x is less than 5")
elif x == 10:
print("x is equal to 10") # This code runs because the elif condition is true
else:
print("x is greater than 10")
Using elif
allows you to handle more than two possible outcomes in your conditional logic. This is particularly useful when dealing with multiple states or cases that require different handling within your program.
The combination of if
, elif
, and else
statements forms a powerful decision-making structure in Python, enabling you to manage complex logical flows effectively.