Nested-if statement in Python Programming
Nested-if Statement in Python: Nested-if statement is also the most important and easiest concept of control flow statements. This statement is very helpful, while or when we need to make a decision (when we have more than one condition to check) based on our problem.
A nested if is a flow control statement that’s the target of another if-statement. By nested-if statements, we mean to use an if-statement inside another if-statement. In Python, it is possible to place one if-statement inside the other if-statement.
We will learn about these flow control statements in detail.
Also, there are other control statements, These are given below:-
- if (already discussed)
- if-else (already discussed)
- if-elif (already discussed)
- if-elif-else (already discussed)
- nested-if
Let’s discuss all above statements in detail one by one:- If, if-else statements,if-elif, and if-elif-else we have discussed already, followed by this article (if-statement, if-else statement,if-elif,if-elif-else), now we discuss nested-if:
(i). Nested-if statement: The nested-if statement’s execution is different from our previous control statements that we have discussed so far. The nested-if statement can be used inside the other if statement. This flow control statement is very helpful when we have to deal with a large number of conditions.
Syntax:
#nested-if statement example x = 21 if(x==21): #first if if(x > 20): #second if print(x) # output # 21
The above given example is the easiest example to understand the nested-if statement.
Note: Here we can also use anything else at the last. If both of the conditions inside if-statements remain false, then the statement inside else: block will execute. Below the given example of a nested if-else statement in python:
Example 1: Example of nested if-else statement in python.
#nested-if statement example x = 18 if(x==23): print(x) if(x==22): print(x) else: print("Inside Else Block") else: print("Condition get False, Hence it didn't enter if condition") # output # Condition get False, Hence it didn't enter if condition
Example 2: Write a program to display the greatest among three numbers using nested if statement.
a = 40 b = 80 c = 70 if(a>b): if(a>c): print("a is greater") if(b>a): if(b>c): print("b is greatest") if(c>a): if(c>b): print("c is greatest") # output # b is greatest
Other Control Flow Statements: