Decisions are an essential part of our life. This is true in the case of programming languages as well. In programs, situations arise when we need to make some decisions, and based on these, the program executes the next block of codes.
The direction of the flow of programming languages is decided by the decision making statements in programming languages. The decision making statements which python supports are as follows.
nested if statement
It is the simplest decision-making statement. It decides whether there will be an execution of a particular statement or not. If a specified condition is True, it gets executed; otherwise, it does not get executed. If statement only accepts Boolean values.
Indentation is used by Python for the identification of a block. Here is a syntax on how indentation is used in if statement.
#if the condition is true, if block
# considers only statement1 to be inside
# its block.
# python program to illustrate If statement
i = 12
if (i> 20):
print (“12 is less than 20”)
print (“I am not in if”)
I am not in if
As the if condition is False so, the next command gets executed and not the block below the if statement.
We saw above that if the condition is true the block gets executed; otherwise, it does not get executed. Suppose we wanted to do something else if the block is false. In such conditions, the else statement comes in handy. Along with the if statement, the else statement allows us to execute a block when the condition is false.
# python program to illustrate If else statement
i = 30;
if (i< 20):
print (“i is smaller than 20”)
print (“i’m in if Block”)
print (“i is greater than 20”)
print (“i’m in else Block”)
print (“i’m not in if and not in else Block”)
i is greater than 20
i’m in else Block
i’m not in if and not in else Block
It means an if statement inside another if statement. Python allows the uses to nest one statement inside another.
# python program to illustrate nested If statement
i = 10
if (i == 10):
# First if statement
if (i< 15):
print (“i is smaller than 15”)
# Nested – if statement
# Will only be executed if statement above
# it is true
if (i< 12):
print (“i is smaller than 12 too”)
print (“i is greater than 15”)
i is smaller than 15
i is smaller than 12 too
Here multiple options are present in front of the user. The execution ofthe if statements take place from top to down. As one condition is true in association of if, the statement associated with it gets executed. The rest of the conditions or ladders are neglected. In case of no true statements, the final else statement is executed.
# Python program to illustrate if-elif-else ladder
i = 20
if (i == 10):
print (“i is 10”)
elif (i == 15):
print (“i is 15”)
elif (i == 20):
print (“i is 20”)
print (“i is not present”)
i is 20