Python Elif (If Elif Else) Statement

In python, elif keyword is a short form of else-if and it useful to define multiple conditional expressions between if and else statements. The elif keyword will combine both if and else statements and create if-elif-else statements.


The if-elif-else statements will contain multiple conditional expressions, but only one boolean expression evaluates to True and execute the respective block of statements.


In the if-elif-else statement, only one if and else blocks are allowed, but you can add multiple elif blocks based on your requirements.

If Elif Else Statement Syntax

In python, if, elif, and else keywords are used to define the conditional if elif else statements. Following is the syntax of defining if elif else statement in python.


if boolean_expression1:
elif boolean_expression2:
elif boolean_expression3:

If you observe the above if elif else statement syntax, the statements inside of if condition will execute only when the boolean_expression returns True otherwise, it will validate the next condition of elif block, and so on. In case if all the defined expressions are False, the else block statements will be executed.


As discussed in the python if and python if-else statement, you need to follow the indentation while creating if, elif, and else block statements; otherwise, you will get build errors (IndentationError).

Python If Elif Else Flow Chart

Following is the flow chart diagram of if elif else statement process flow in python.


Python if elif else statements flow chart diagram


If you observe the above if elif else statement flow chart diagram, if block of statements will execute only when the defined condition is True otherwise, it will move to the next elif condition, and so on. If all the conditions are failed to execute, else block statements will be executed.

Python If Elif Else Example

Following is the example of if elif else statement in python to execute the required block of statements based on the defined Boolean expression.


x = 30
y = 50
if x > y:
    print("x is greater than y")
elif y > x:
    print ("y is greater than x")
    print("x and y are equal")

If you observe the above example, we defined if elif else statements with boolean expressions and followed the indentation to define the block of statements inside if elif else statements.


When you execute the above python program, you will get the result as shown below.


y is greater than x

This is how you can use elif statement to include multiple conditions in between if and else statements based on your requirements.