How do you create a nested IF statement in python

In Python, a nested if statement means placing one if statement inside another, allowing you to check multiple conditions in a hierarchical or dependent manner.

 

Basic Syntax of Nested if in Python:


 

if condition1: if condition2: # Code runs if both condition1 and condition2 are True print("Both conditions are true") else: print("Only condition1 is true") else: print("Condition1 is false")

 

Example: Check if a number is positive and even


 

 

num = 10 if num > 0: if num % 2 == 0: print("The number is positive and even") else: print("The number is positive but odd") else: print("The number is not positive")

Output:

The number is positive and even

 

Pro Tip:

You can also use elif and logical operators (and, or) if nesting becomes too complex:


 

if num > 0 and num % 2 == 0: print("The number is positive and even") elif num > 0: print("The number is positive but odd") else: print("The number is not positive")

 

  All Comments:   0

Top Services From How do you create a nested IF statement in python

Top Keywords From How do you create a nested IF statement in python