elif Statement
Sometimes, the programmer may want to evaluate more than one condition. This can be done using an elif
statement.
An elif
statement works on the following principle:
- Execute the block of code inside the
if
statement if the initial expression evaluates toTrue
. After execution, return to the code outside theif
block. - Execute the block of code inside the first
elif
statement if the expression inside it evaluates toTrue
. After execution, return to the code outside theif
block. - Execute the block of code inside the second
elif
statement if the expression inside it evaluates toTrue
. After execution, return to the code outside theif
block.- ...
- Execute the block of code inside the nth
elif
statement if the expression inside it evaluates toTrue
. After execution, return to the code outside theif
block. - Execute the block of code inside the
else
statement if none of the expressions evaluate toTrue
. After execution, return to the code outside theif
block.
Example:
num = 0
if (num < 0):
print("Number is negative.")
elif (num == 0):
print("Number is Zero.")
else:
print("Number is positive.")
Output:
Number is Zero.