The purpose of the if construct is to
execute some statements only when certain conditions are
true.
Here is the most general form of an if
construct:
ifE0:B0elifE1:B1elif ...: ... else:Bf
In words, this construct means:
If expression is true,
execute block E0.
B0
If expression is false but
E0 is true,
execute block E1.
B1
If there are more elif clauses,
evaluate each one's expression until that expression
has a true value, and then execute the corresponding
block.
If all the expressions in if and elif clauses are false, execute block .
Bf
An if construct may have zero or more
elif clauses. The else
clause is also optional.
Examples:
>>> for i in range(5): ... if i == 0: ... print "i is zero", ... elif i == 1: ... print "it's one", ... elif i == 2: ... print "it's two", ... else: ... print "many", ... print i ... i is zero 0 it's one 1 it's two 2 many 3 many 4 >>> if 2 > 3: print "Huh?" ... >>> if 2 > 3: print "Huh?" ... else: print "Oh, good." ... Oh, good. >>> if 2 > 3: print "Huh?" ... elif 2 == 2: print "Oh." ... Oh.