Friday, 20 July 2012

The else Statement of Python


An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if expression in the if expression resolves to 0 or a false value.

The else statement is an optional statement and there could be at most only one else statement following if.

The syntax of the if….else statement is:

If expression :
            Statement(s)
else:
            Statement(s)

Example:

# ! /usr/bin/python

var1 = 100
if var1:
            print “1 – Got a true expression value”
            print var1
else
            print “1 – Got a true expression value”
            print var1
var2 = 0
if var2:
            print “2 – Got a true expression value”
            print var2
else
            print “2 – Got a true expression value”
            print var2
print  “Good bye”


This will produce following result:

1 – Got a true expression value
100
2 – Got a true expression value
0
Good bye!

No comments:

Post a Comment