In python, if else statement will have optional else
block statements along with if
statements, and it is useful to execute the block of code/statements based on the defined conditions.
The if else statement is an extension of the if statement in python. In if-else statement, if
condition statements will execute whenever the defined boolean expression returns True
otherwise, the else
block statements will be executed.
In python, if
and else
keywords are used to define the conditional if-else statements. Following is the syntax of defining if-else statement in python.
If you observe the above if-else statement syntax, the statements inside of if
condition will execute only when the boolean_expression returns True
otherwise, else
block statements will be executed.
As discussed in the python if statement, you need to follow the indentation to create if/else block statements; otherwise, you will get build errors (IndentationError
). To know more about specifying the indentation in python, refer to Python basic syntaxes.
Following is the flow chart diagram of the if-else statement process flow in python.
If you observe the above if-else statement flow chart diagram, if
block of statements will execute only when the defined condition is True; otherwise, the else
statements will be executed.
Following is the example of an if-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-else statements with boolean expressions and followed the indentation to define the block of statements inside if-else statements.
When you execute the above python program, you will get the result as shown below.
In the if-else statement, if you have only one line statement to execute either in if/else, you can write the complete if-else conditional statement in a single line like as shown below.
When you execute the above python program, you will get the result like as shown below.
In python, writing if-else statements in a single line will also call as ternary operators.
If required, you can also include multiple if-else statements in one line like as shown below.
When you execute the above python program, you will get the result as shown below.
If you create if-else statements inside of other if-else statements, we will call them nested if-else statements.
To learn more about nested if-else statements, refer python nested if-else.