Next / Previous / Contents / TCC Help System / NM Tech homepage

23.5. The if statement: Conditional execution

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:

if E0:
    B0
elif E1:
    B1
elif ...:
    ...
else:
    Bf

In words, this construct means:

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.