We consider this article to be an extension of if..else statement in Python. if statements inside a if statement are Nested if statements. In a regular if..else statement, we saw how the interpreter just checks for a specific condition - if it comes out to be True then, it execute some code else it executes the other one.
But, with nested if - we can put more checks with the first and subsequent if statements itself. In other words, we can have multiple variations in the condition which we are about to check.
The syntax for nested if statements in Python -
if (condition X): if (condition Y): execute A if (condition Z): execute B
We here, check for condition X, if it satisfies then we move to condition Y. If the condition Y also comes out as True then, it executes B. If condition Z is False then, it won't execute B. If condition X itself was False then, it wouldn't go further to check for nested ifs.
We cover it more with relevant example next.
Nested if in Python
Example. Check for positive integers which fall between 10 to 50 -
num = int(input("Enter an integer value: ")) if (num > 0): print("It's a positive integer!!") if (num > 10) and (num < 50): print("The input integer falls between 10 and 50") else: print("The input integer doesn't fall between 10 and 50") else: print("It's a negative integer!!")
Note: Please take of indentation while writing the code. Otherwise, it may result in an Error.
Here, we have asked the user to input an integer value and stored it in variable num. If the input is greater is than zero then, it would print - "It's a positive integer!!" otherwise it would print - "It's a negative integer!!". If the condition num>0 is True then, it would move to check if the input falls between 10 and 50 and return with the appropriate outcome accordingly.
Check for multiple input values to see which section of code is executed.
We reiterate that see the positioning of two statements in the above code -
if (num > 0): and
if (num > 10) and (num < 50): See how nested if statements work in unison. It moved to the other if statement only when the first condition was True.
In conclusion, we have covered nested if statements in Python here.