Control Flow: The if
, elif
, else
Statements
The if
, elif
, else
Statements
When we need to check a related sequence of conditions that are more than two, we can use the intermediate elif
conditional statements.
else
part, the elif
part is also optional, i.e. you do not have to include an elif
section if it is not required.elif
statements has to be preceded by a single if
statement, starting the conditional sequence.elif
statements as necessary in the comparison sequence.else
statement cannot precede any elif
statement in the same conditional control sequence.A comparison statement sequence begins with a single if
statement, continues with zero or more elif
statements, and optionally ends with a single else
statement.
The else
statement does not specify any condition, as it is the default code block to be executed if none of the conditions specified before that else
block (inside the same conditional sequence) were evaluated to True
.
y = int(input("Enter a number please: "))
x = y + 3
print("x =", x)
if (x <= 10):
print("x is less than or equal to 10")
elif (x < 20):
print("x is greater than 10 and less than 20")
else:
print("x is greater than or equal to 20")
All conditional statements in the same if
-elif
-else
sequence are mutually exclusive, i.e. if any one of the conditional statements is evaluated to True
, the rest of the conditional statements of the same conditional sequence are skipped no matter if they could also be evaluated to True
for that specific case.
elif
represents the case check as else-if and the following code samples are functionally equivalent:
x = int(input("Enter a number please: "))
print("x =", x)
if (x < 10) :
print("x is less than 10")
else:
if (x % 2 == 0):
print("x is an even number")
else:
print("x is an odd number")
x = int(input("Enter a number please: "))
print("x =", x)
if (x < 10) :
print("x is less than 10")
elif (x % 2 == 0):
print("x is an even number")
else:
print("x is an odd number")
Attention: Beware of the indentation in both examples.
Inserting statements other than elif
or else
at the same indentation level as the if
statement is not allowed since it would terminate the conditional sequence and any of the following elif
and else
statements will be detached from the initial if
, which they are supposed to be bound to.
The following example will cause an error since the print("Now checking for even odd status")
statement breaks the conditional sequence.
y = int ( input("Enter a number please: ") )
x = y + 3
print("x =", x)
if (x <= 10) :
print("x is less than or equal to 10")
print("Now checking for even odd status")
elif (x < 20) :
print("x is greater than 10 and less than 20")
else:
print("x is greater than or equal to 20")