Skip to main content

Python Nested if Statement

There may be a situation when we can check for another condition after a condition resolves to true. In such a situation, we can use the nested if construct.  A if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.

Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so it must be avoided if we can.

Syntax:

if (expression1):
    (statement)
    if (expression2):
        (statement)
    elif (expression3):
        (statement)
    elif (expression4):
        (statement)
    else:
        (statement)
else:
    (statement)

Flow Chart:

Python Nested if statement

Example:

x = 53

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

Output:

Above ten,
and also above 20!
Tags
Submitted by devanshi.srivastava on June 7, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.