Friday, 20 July 2012

The Nested if…elif…else Construct:


There may be a situation when you want to check for another condition after a condition resolves a condition resolves to true. In such a situation, you can use the nested if construct.

In a nested if construct, you can have an if…elif…else construct inside another if…elif…else construct.
The syntax of the nested if…elif…else construct may be:

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

Example:

#!/usr/bin/python

Var = 100
If var < 200
  print “Expression value is less than 200”
if var == 150:
  print “which is 150”
elif var == 100:
   print “Which is 100”
elif  var == 50:
   print  “Which is 50”

elif var < 50:
    print  “Expression value is less than 50”
else:
   print  “could not find true expression ”

print  “Good bye!”

This will produce following result:

Expression value is less than 200
Which is 100
Good bye!

No comments:

Post a Comment