Nested if else in python

Rumman Ansari   Software Engineer   2022-08-17   667 Share
☰ Table of Contents

Table of Content:


  • What you will learn in this section:
    1. What is nested if?
    2. Flow chart of nested if else.
    3. Syntax of nested if else.
    4. Examples nested if else with explanation

    Syntax:

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

    Example 1:

    # python program to illustrate nested If statement
     
    i = 16
    if (i > 10):    
        #  First if statement
        if (i < 15):
            print("i is smaller than 15")
              
        # Nested - if statement
        # Will only be executed if statement above
        # it is true
        if (i < 12):
            print("i is smaller than 12 too")
        else:
            print("i is greater than 15")
    
    i is greater than 15
    

    Example 2:

    # Example of nested if else
    
    age = int(input(" Please Enter Your Age Here:  "))
    if age < 18:
            print(" You are not Eligible to Work ") 
    else:
        if age >= 18 and age <= 60:
            print(" You are Eligible to Work ") 
        else:
            print(" You are too old to work as per the Government rules") 
    
     Please Enter Your Age Here:  70
     You are too old to work as per the Government rules