nested if else in python


  • It is perfectly all right if we write an entire if...else construct within either the body of the if statement or the body of an else statement. This is called ‘nesting’of ifs.
  • Nested if...else statements has ability to control program flow based on multiple levels of condition.
  • There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one
  • Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

Syntax

    if expression:
       statement(s)
    else:
       if expression:
          statement(s)
       else:
            statement(s)

Flow Diagram

    nested if else statement in python language

Example

    if x == y:
       print('x and y are equal')
    else:
      if x < y:
        print('x is less than y')
      else:
        print('x is greater than y')
    

Expression

  • The outer conditional contains two branches. The first branch contains a simple statement.
  • The second branch contains another if statement, which has two branches of its own.
  • Those two branches are both simple statements, although they could have been conditional statements as well.
  • Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avoid them when you can.