If Else in Python
If Else in Python
If else in Python are a set of control statements that literally control flow of code. Change in the flow usually depends upon a set of conditions either being true or false though it is not important to specify which path to take if the condition happens to be false. It is a variant of if else statement. Majorly, there are three types of if control statements:
- If Statement
- If Else Statement
- Elif Statement
If Statement in Python
It executes a block or a piece of code if a boolean expression evaluates to be true. If only a single statement needs to be executed upon successful evaluation, then it can be placed under the if-expression with proper indentation. If the action is made up of more than one statement, then all the statements should have the same indentation where first line following the rules of indentation in Python. If the if-expression turns out to be false after evaluation, then the if-block is skipped like it never existed and the code is executed normally.
Syntax of If Statement:
if condition: statements
Flow Diagram of If Statement:
Example of If Statement:
# Python program to exemplify if statement num = 22 if num % 22 == 0: print(num," is divisible by 11.")
Output:
22 is divisible by 11.
If Else Statement in Python
If part of if-else statement in Python is same as the if statement. Else part of if-else statement comes into the picture when the if-expression evaluates to boolean false. This implies that if else statement has two blocks of actions to be executed and none of them can execute one after the other. Only one out of the executes at a time. If the if boolean expression if true, the if-block executes, if it is false, then else-block executes.
Syntax of If Else Statement:
if condition: statements else: statements
Flow Diagram of If Else Statement:
Example of If Else Statement:
# Python program to exemplify if else statement num = 21 if num % 22 == 0: print(num," is divisible by 11.") else: print(num," is not divisible by 11.")
Output:
21 is not divisible by 11.
Elif Statement in Python
It is used when more than one condition needs to be checked. If the first condition evaluates to false, then the next condition is examined and if it is too evaluated to true, then other condition is evaluated. It ends with an else block which is reached only if none of the condition evaluate to true.
Syntax of Elif Statement:
if condition: statements elif condition: statements ... ... ... else: statements
Flow Diagram of Elif Statement:
Example of Elif Statement:
# Python program to exemplify elif statement num = -21 if num > 0: print(num," is a positive number.") elif num < 0: print(num," is a negative number.") else: print(num," is neither positive nor negative.")
Output:
-21 is a negative number.