Python If Else Statement
Selection statements
During the execution of the program we may not wish to execute all set of statements sequentially. Some times we may wish to select between the set of statements based on some conditions. Based on the test condition evaluation, the flow is determined inside the program. Let’s have look at few of them.
if (simple if):
It is a conditional statement used for decision making in python. In if statement, the test condition is evaluated and the statements inside the if block are executed only if the evaluated condition is true. In if statement, we have only one set of statements to select based on the test condition. So, it is also called as One-way selection statement.
Below is the syntax of simple if statement:
CODE/PROGRAM/EXAMPLE
//Program Example:
a=10
if(a>0):
print(“positive integer”)
Output:
positive integer
if-else:
It is a conditional statement used for selection between two set of statements based on the evaluation of test condition. The statements inside the if block are executed only if the evaluated condition is true. Otherwise statements inside the else block are executed. As we have two set of statements to select based on the test condition, it is also called as Two-way selection statement.
Below is the syntax of if-else statement:
CODE/PROGRAM/EXAMPLE
//Program Example:
a=-10
if(a>0):
print(“positive integer”)
else:
print(“Not a positive integer”)
Output:
Not a positive integer
else-if ladder:
It is a conditional statement used for selection between multiple set of statements based on multiple test conditions. The various test conditions are provided inside each if statement. Whenever the test condition is evaluated as True, the statements inside the corresponding if block are executed and the control comes out of the else-if ladder. If none of the test conditions are evaluated as True, the statements inside the else block are executed. As we have multiple set of statements to select based on the test conditions, it is also called as multi way selection statement.
In else-if ladder the conditions are evaluated from the top of the ladder downwards. As soon as a true condition is found, the statement associated with it is executed skipping the rest of the ladder.
Below is the syntax of else-if ladder statement:
CODE/PROGRAM/EXAMPLE
//Program Example:
a=0
if(a>0):
print(“positive integer”)
elif(a<0):
print(“negative integer”)
else:
print(“it’s zero”)
Output:
it’s zero
Nested if:
An if statement within another if statement is known as nested if statement. Similarly, any decision logic can be written within an else statement also.
Have a look at the below example of nested if:
CODE/PROGRAM/EXAMPLE
//Program Example :
num1=10
num2=20
num3=30
if(num1>num2):
if(num1>num3):
print(“num1 is greater”)
else:
print(“num3 is greater”)
elif(num2>num3):
print(“num2 is greater”)
else:
print(“num3 is greater”)
Output:
num3 is greater