Python Else-If Statement Example
Published on Aug. 22, 2023, 12:15 p.m.
Certainly! The Python else-if statement is actually written as elif
. It is used to test multiple conditions in sequence and execute a different block of code depending on which condition is met first. Here’s an example:
x = 5
if x > 5:
print("x is greater than 5")
elif x < 5:
print("x is less than 5")
else:
print("x is equal to 5")
In this example, we use the if-elif-else statement to check if the variable x
is greater than, less than, or equal to 5. We first check if x
is greater than 5 using the if
statement. If the condition is not met, we move on to the elif
statement to check if x
is less than 5. If that condition is also not met, we execute the else
block of code, which indicates that x
must be equal to 5.