The purpose of an if statement is to
perform certain actions only in certain cases.
Here is the general form of a simple
“one-branch” if statement.
In this case, if some condition is true, we want to execute
some sequence of statements, but if C is not true, we don't want to
execute those statements.
C
ifC:statement1statement2...
Here is a picture showing the flow of control through a
simple 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.
When the if statement is executed, the
condition
is evaluated, and converted to a Cbool
value (if it isn't already Boolean). If that value is
True, the block is executed; if the value
is 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 when AC is true,
but perform some different action when BC is
false. The general form of this construct is:
ifC:block A... else:block B...

As with the single-branch if, the
condition
is evaluated and converted to Boolean. If the result
is CTrue, is executed; if block
AFalse, is executed instead.
block B
>>> 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 if or else,
instead of placing them in an indented block. Use a
semicolon “;” 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
of “elif clauses” after an
if, and before the else
clause if there is one. Here is the most general form of
a Python if statement:
ifC1:block1elifC2:block2elifC3:block3... else:blockF...

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