In python, elif
keyword is a short form of else-if a
nd 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.
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 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).
Following is the flow chart diagram of if elif else
statement process flow in python.
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.
Following is the example of if elif else
statement in python to execute the required block of statements based on the defined Boolean expression.
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.
This is how you can use elif
statement to include multiple conditions in between if
and else
statements based on your requirements.