Skip to content

Nested if statement in Python

  • by

Python Nested if statement means have if statements inside if statements. It is used to apply multiple conditions to make one decision, and those conditions are dependent on each other.

if (condition1):
   # Executes when condition1 is true
   if (condition2): 
      # Executes when condition2 is true
   # if Block is end here
# if Block is end here

Nested if statement in Python

Simple example code.

x = 30

if x > 10:
    print("Above 10,")
    if x > 20:
        print("and also above 20!")
    else:
        print("but not above 20.")

Output:

Nested if statement in Python

In a nested, if construct, you can have an if…elif…else construct inside another if…elif…else construct.

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"

Here’s a simple example:

x = 10
y = 5

if x > 5:
    print("x is greater than 5")
    if y > 2:
        print("y is also greater than 2")
    else:
        print("y is not greater than 2")
else:
    print("x is not greater than 5")

In this example, there’s an outer if statement checking if x is greater than 5. If it is, it prints “x is greater than 5” and then checks if y is also greater than 2. Depending on the value of y, it prints different messages. If x is not greater than 5, it simply prints “x is not greater than 5”.

Do comment if you have any doubts or suggestions on this Python if statement topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading