Overview of Nested if...else Statement

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.

Syntax

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

 

Flow Diagram

 

Flow Diagram of nested if else statement

 

Example

var = 10
if var < 20:
   print "value is less than 20"
   if var == 15:
      print "Value is 15"
   elif var == 10:
      print "Value is 10"
   elif var == 5:
      print "Value is 5"
   elif var < 5:
      print "value is less than 5"
else:
   print "Bye"

print "Good bye!"

 

Output

value is less than 20
value is 10
Good bye!