Python Nested if block

Previous
Next

Nested – If:

  • Defining if block inside another if block.
  • Inner block condition evaluates only when outer condition is valid

Simple code:

if True:
    print("A")
    if True:
        print("B")

Output it:

if False:
    print("A")
    if True:
        print("B")

We can define else block for every nested if block:

if True:
    print("A")
    if False:
        print("B")
        if True:
            print("C")
        else:
            print("D")
    else:
        print("E")
else:
    print("F")

Number divisibility test with 3 and 5:

n=int(input("Enter n value :"))
if n%3==0:
    if n%5==0:
        print("divisible by 3 and 5")
    else:
        print("divisible by 3 not 5")
else:
    if n%5==0:
        print("divisible by 5 not 3")
    else:
        print("not divisible by 3 and 5")

Leap year program using nested if:

n=int(input("Enter year :"))
if n%100==0:
    if n%400==0:
        print("Leap")
    else:
        print("Not leap")
else:
    if n%4==0:
        print("Leap")
    else:
        print("Not leap")
Previous
Next

One Response

  1. Quincy Kawamoto April 11, 2021

Add Comment

Courses Enquiry Form