elif Statement

 

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 if statement if the initial expression evaluates to True. After execution return to the code out of the if block.
  • execute the block of code inside the first elif statement if the expression inside it evaluates True. After execution return to the code out of the if block.
  • execute the block of code inside the second elif statement if the expression inside it evaluates True. After execution return to the code out of the if block.
    .
    .
    .
  • execute the block of code inside the nth elif statement if the expression inside it evaluates True. After execution return to the code out of the if block.
  • execute the block of code inside else statement if none of the expression evaluates to True. After execution return to the code out of the if 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.