In this article, we’ll learn what nested if in Python is and how to properly use it in Python code.
We’ll be using an easy but proper practical code example and explaining it in detail so you can have a better idea how nested if in Python works.
After reading this post, I am sure you’ll be able to incorporate nested if statement in your code with ease.
What is Nested If in Python?
Nested if means if inside if. By using nested method, we can apply multiple conditions on same/different values.
For instance, assume that the condition is satisfied that a specific value is lesser than 16, now we want to apply another condition on it to check whether its greater than 10 or not. This is how the nested if works.
Let’s first understand the syntax of nested if in Python. After that, we’ll understand it using a practical example.
Syntax of Nested If
if condition: if condition: //run this if condition is satisfied else: //run this if condition is not satisfied else: //run this if condition is not satisfied
As you can see here, we first have an if condition. If its satisfied then it’ll run the second if condition which is a nested if. Use indentation for that, which means its in the body of first if statement.
If the second condition is satisfied then its body will run, if not then its else body will get executed.
So this is how you can use multiple nested if conditions as well.
Implementing Nested If in Python (Easy Example)
We’ll be applying multiple conditions on the same value in this example. See below code:
val=15 if val>10: if val<16: if type(val) == int: print('The value is greater than 10, less than 16 and its of integer type') else: print('Not of integer type') else: print('Not less than 16') else: print('Value is not greater than 10')
Explanation
- First, we have initialized an integer.
- We have checked that whether its greater than 10 or not, if yes then execute this if statement’s body, if not then execute the else block.
- In its body, we’ve a nested if statement in which a condition is specified that if the variable value is less than 16, only then execute its body, if not then run the else statement.
- We’ve another nested if statement which is used to check the datatype of our value.
- All the conditions were true.
Output
The value is greater than 10, less than 16 and its of integer type
So this is how you can easily use nested if in Python. Hope you like this post.
Feel free to ask if you still have any questions related to the implementation or customization of Python nested if statement. I’ll be happy to answer them.
Conclusion
To conclude, hope you now have a clear practical idea of how to use and customize nested if in Python. I’ll be happy to have your feedback on this post. Thank you for reading it.