Python Nested If Else Statement

When we place an ‘if statement’ inside another ‘if statement’, it is a nested if statement in Python.

It is a very common to use in Python programming. Python nested if statement is useful when we want to check for another condition after a condition evaluates to true.

An inner if statement can also contain another if statement. Indentation plays an important role in figuring out the level of nesting.

Syntax of Nested If Statement in Python


The general syntax to declare nested if statement in a Python program is as follows:

# Outer if statement.
if condition-1:
# Inner if statement declared inside the outer if statement.
    if condition-2:
        statement to be executed when the condition-1 and condition-2 are true.

In the above syntax, if the condition-1 in the outer if statement is true, Python will follow to check another inner if condition-2. If it is true, the statement inside inner if block will execute. Otherwise, the statement inside inner if block will not execute if the condition-2 evaluates to false.

If condition-1 in the outer if statement is false, Python will not go to check the condition-2 in the inner if statement.

Nested If Example Programs


Let’s understand nested if statement with the help of some example programs.

Example 1:

x = 20
y = 10
z = 5
# Outer if statement.
if x > y:
    if y > z: # Nested inner if statement.
        print('Hello')
Output:
      Hello

In this example, we have placed an if statement inside another if statement to check for another condition. Python first evaluates the condition x > y to true. Since x is greater than y, the condition x > y is true. Then, Python will check the inner condition y > z to true.


Since y is greater than z, the condition is true. Hence, Python will execute the statement inside inner if block and display the message ‘Hello’.


Example 2:

x = 20
y = 10
z = 5
# Outer if statement.
if x > y:
    if y < z: # Nested inner if statement.
        print('Hello')
    print('Hi')
Output:
      Hi

In this example, Python first check the outer if condition x > y. Since x is greater than y, so the condition is true. Then, Python goes to check the inner condition y < z.

Since the condition is false, therefore, the statement inside the inner if block will not execute. However, the outer if condition is true, so Python will print the message ‘Hi’ on the console because the print statement belongs to the outer if block.


Example 3:

x = 20
y = 10
z = 5
# Outer if statement.
if x < y: 
    if y > z: # Nested inner if statement.
        print('Hello')
    print('Hi')

In this example, the outer if condition-1 is false, none of the statements inside the outer if block will execute.

Nested If Else Statement in Python


When we place an ‘if else’ statement inside another ‘if statement’ or ‘if else’ statement, it is called nested if else statement in Python. In fact, we can nest any number of ‘if else’ statement inside one another.


The general syntax to declare a nested if else statement is as follows:

# Outer If else statement.
if condition-1:
    statements to be executed if condition-1 is true.
# Inner if else statement.
    if condition-2:
       statements to be executed when the condition-1 and condition-2 are true.
    else:
       statements to be executed when the condition-1 is true and condition-2 is false.
else:
    statements to be executed when the condition-1 is false.    

Let’s take some examples based on the nested if else statement in Python.

Nested if-else Example Program


Example 1:

x = 20
y = 10
z = 5
# Outer if else statement.
if x > y:
    print('Outer if block')
    if y < z: # Nested inner if else statement.
        print('Inner if block')
    else:
        print('Inner else block')
else:
    print('Outer else block')
Output:
      Outer if block
      Inner else block

In this example, we have placed an if-else statement inside another if-else statement to check for another condition. The outer if condition x > y evaluates to true. Therefore, Python prints the message ‘Outer if block’ and skips the execution of outer else block statement.

After checking the outer if condition, Python evaluates the inner if condition y < z. The condition y < z is false, the inner if block will not execute. Python will execute the statement inside the inner else block and prints the message ‘Inner else block’.


Example 2:

Let’s write a Python program to check whether a number is divisible by 2 and 3.

# Take a number as input from the user.
num = int(input('Enter a number that you want to check divisible: '))
# Outer if else statement.
if num % 2 == 0:
    if num % 3 == 0: # Nested inner if else statement.
        print('The number is divisible by 2 and 3.')
    else:
        print('The number is divisible by 2, but not divisible by 3.')
else:
    if num % 3 == 0:
        print('The number is divisible by 3, but not divisible by 2')
    else:
        print('The number is not divisible 2 and 3.')
Output:
      Enter a number that you want to check divisible: 8
      The number is divisible by 2, but not divisible by 3.

      Enter a number that you want to check divisible: 15
      The number is divisible by 3, but not divisible by 2

      Enter a number that you want to check divisible: 12
      The number is divisible by 2 and 3.

      Enter a number that you want to check divisible: 5
      The number is not divisible by 2 and 3.

In this example, we have placed two if-else statements inside another if-else statement, one in the if block and another in the else block.

Example 3:

Let’s write a program in Python using nested if else statement to check whether a number is zero, positive, or negative.

num = int(input('Enter a number that you want to check: '))
# Outer if else statement.
if num >= 0:
    if num == 0: # Nested inner if else statement.
        print('Number is zero.')
    else:
        print('Number is positive.')
else:
    print('Number is negative.')
Output:
      Enter a number that you want to check: 2
      Number is positive.

      Enter a number that you want to check: -2
      Number is negative.

In this example, Python first tests the expression num >= 0. If it is true, Python follows the inner if condition num == 0 and evaluates to true.

If the inner if condition num == 0 is also true, the inner if block message will display as ‘Number is zero’, otherwise, display as ‘Number is positive’.

Python evaluates the expression num >= 0 to false, it follows its own else block without checking the inner if condition and display as “Number is negative”. This is because the number is neither zero nor positive.


Example 4:

Let’s write a program in Python using nested if statement, check the following:

  • If age < 18; display ‘You are minor and not eligible to cast vote.’
  • If age >= 18 and age < 60; display ‘You are young and eligible to cast vote.’
  • Otherwise, display ‘You are a senior citizen person and will be given special care to cast vote.’
age = int(input('Please enter your age: '))
# Outer if else statement.
if age < 18:
    print('You are minor and not eligible to cast vote.') 
else: 
    if age >= 18 and age < 60:
        print('You are young and eligible to cast vote')
    else:
        print('You are a senior citizen person and will be given special care to cast vote.')
Output:
      Please enter your age: 17
      You are minor and not eligible to cast vote.
      Please enter your age: 42
      You are young and eligible to cast vote

In this example, we have nested else block by placing another if-else statement inside the else block. If Python evaluates the if condition (age < 18) to true, the statement inside the if block will execute and else block of if part will not execute.

If Python evaluates to false, else block of if part will execute. Inside the else block, Python will check the inner if condition (age >= 18 and age < 60) to true.

If the condition is true, if block statement will execute otherwise, else block statement will execute.


Example 5:

Let’s write a program in Python to check whether a year is a leap year.

# Program to check a year is leap year or not.
year = int(input('Please enter a year: '))
if year % 4 == 0:
    if year % 100 == 0:
        if year % 400 == 0:
            print(year,'is a leap year.')
        else:
            print(year,'is not a leap year.')
    else:
        print(year,'is a leap year.')
else:
    print(year, 'is not a leap year.')
Output:
      Please enter a year: 1968
      1968 is a leap year.
      Please enter a year: 2024
      2024 is a leap year.
      Please enter a year: 2023
      2023 is not a leap year.

In this example, we have checked many leap years using nested if statement. A year which is perfectly divisible by 4 is leap years. For example, years such as 2024, 2012, 2004, 1968, etc. are leap years.

Century year ending with 00 is a leap year when it is divisible by 400. For example, 2000, 1200, 1600, 2400, etc. are leap years but 1700, 1800, 1900, etc. are not leap years.

Nested If-elif-else Statement in Python


When we place an ‘if elif else’ statement inside another ‘if elif else’, then it is called nested if elif else statement in Python. We can nest any number of these statements inside one another.

The general syntax to nest if-elif-else statement inside another if-elif-else statement is as follows:

# Outer if-elif-else statement.
if condition-1:
    statement to be executed when the condition-1 is true.
# Inner if-elif-else statement.
    if condition-2:
        statement to be executed when the condition-1 and condition-2 are true.
    elif condition-3:
        statement to be executed when the condition-1 is true and condition-3 is true.
    . . . . . .
    else:
        statement to be executed when the condition-1 is true and none of the above is true.
# Outer elif statement.
elif condition-4:
    statement to be executed when the condition-1 is false and condition-4 is true.
# Outer else statement. 
else:
    statement to be executed when the condition-1 and condition-4 are false.

Let’s take an example program based on the nested if-elif-else statement in Python.

Nested if-elif-else Example Program


Example 1:

Let’s write a program in Python to make a simple calculator to calculate the addition, subtraction, multiplication, and division of two numbers. Take two numbers as input from the user.

# Program to make a simple mathematical calculator.
opr = input('Please enter an operator [+, -, *, or /]: ')
if(opr == '+' or opr == '-' or opr == '*' or opr == '/'):
    n1 = int(input('Please enter your first number: '))
    n2 = int(input('Please enter your second number: '))
    if(opr == '+'):
        sum = n1 + n2
        print("Sum of",n1,'and', n2,'=', sum)
    elif(opr == '-'):
        if(n1 > n2):
            diff = n1 - n2
        else:
            diff = n2 - n1
        print('Difference between',n1,'and',n2,'=', diff)
    elif(opr == '*'):
        multiply = n1 * n2
        print('Multiplication of',n1,'and',n2,'=', multiply)
    elif(opr == '/'):
        if(n1 == 0 or n2 == 0):
            print('Numbers must be positive.')
        else:
            div = n1 / n2
            print('Division of',n1,'by',n2,'=', div)
else:
    print('Sorry, you have entered an invalid operator. Please choose any of these +, -, *, or /.')
Output:
       Please enter an operator [+, -, *, or /]: +
       Please enter your first number: 20
       Please enter your second number: 50
       Sum of 20 and 50 = 70

       Please enter an operator [+, -, *, or /]: /
       Please enter your first number: 50
       Please enter your second number: 10
       Division of 50 by 10 = 5.0

In this tutorial, you have learned nested if elif else statement in Python with the help of various example programs. I hope that you will have understood the basic points and concepts of nested if statement. Stay tuned with the next tutorial where we will discuss about loops in Python with the help of examples.
Thanks for reading!!!