The purpose of an
if statement is to
perform certain actions only in certain cases.
Here is the general form of a simple
In this case, if some condition
is true, we want to execute
some sequence of statements, but if
is not true, we don't want to
execute those statements.
Here is a picture showing the flow of control through a
if statement. Old-timers will
recognize this as a flowchart.
There can be any number of statements after the
if, but they must all be indented, and all
indented the same amount. This group of statements
is called a block.
if statement is executed, the
is evaluated, and converted to a
value (if it isn't already Boolean). If that value is
True, the block is executed; if the value
False, the block is skipped.
Here's an example:
>>> half = 0.5 >>> if half > 0: ... print "Half is better than none." ... print "Burma!" ... Half is better than none. Burma!
Sometimes you want to do some action
C is true,
but perform some different action
false. The general form of this construct is:
block A... else:
As with the single-branch
is evaluated and converted to Boolean. If the result
is executed; if
is executed instead.
>>> half = 0.5 >>> if half > 0: ... print "Half is more than none." ... else: ... print "Half is not much." ... print "Ni!" ... Half is more than none.
Some people prefer a more “horizontal”
style of coding, where more items are put on the same
line, so as to take up less vertical space. If you
prefer, you can put one or more statements on the same
line as the
instead of placing them in an indented block. Use a
;” to separate
multiple statements. For example, the above example
could be expressed on only two lines:
>>> if half > 0: print "Half is more than none." ... else: print "Half is not much."; print "Ni!" ... Half is more than none.
Sometimes you want to execute only one out of three or
four or more blocks, depending on several conditions.
For this situation, Python allows you to have any number
elif clauses” after an
if, and before the
clause if there is one. Here is the most general form of
So, in general, an
if statement can have
zero or more
elif clauses, optionally
followed by an
else clause. Example:
>>> i = 2 >>> if i==1: print "One" ... elif i==2: print "Two" ... elif i==3: print "Three" ... else: print "Many" ... Two
You can have blocks within blocks. Here is an example:
>>> x = 3 >>> if x >= 0: ... if (x%2) == 0: ... print "x is even" ... else: ... print "x is odd" ... else: ... print "x is negative" ... x is odd