Python: “if then else” Example

By Xah Lee. Date: . Last updated: .

Example of “if” statement:

#-*- coding: utf-8 -*-
# python

# example of if

x = 1
if x == 1:
    print "yes"

Example of “if else”:

#-*- coding: utf-8 -*-
# python

# example of if else

y = 2
if y == 1:
    print "yes"
else:
    print "no"

Example of “if else” chain. Note it's elif:

#-*- coding: utf-8 -*-
# python

# example of if else chain

z = 2
if z < 0:
    print "z neg"
elif z == 0:
    print "z zero"
elif z == 1:
    print "z one"
else:
    print "z other"