next up previous contents
Next: for loops Up: Programming Previous: Truth, Falsehood and Logical   Contents


if statement

The if statement, along with optional elif and/or else statements is the basic tool in python for performing conditional execution. The basic form of the statement can be summarized as:
         if expression :
            statement(s)
         elif expression:
            statement(s)
         elif expression:
            statement(s)
              . . .
         else:
            statements
Python evaluates the expression after the if, and, if it is true, carries out the statement(s) which follow; if it is not true, it proceeds to the elif statement (if there is one), and tests that expression. It continues testing the expressions associated with any elif statements, and, once it finds an expression that is true, it carries out the corresponding statement(s) and jumps to the statement following the end of the if block. If it doesn't encounter any true expressions after trying all the elif clauses, and there is an else statement present, it will execute the statements associated with the else; otherwise, it just continues with the statement following the if block. Notice that once python encounters a true expression associated with an if or elif statement, it carries out the statements associated with that if or elif, and doesn't bother to check any other expressions. One implication of this is that if you need to test a number of possibilities where only one can be true, you should always use a set of if/elif clauses so that no extra work is done once the true expression has been found. For example, suppose we wish to do one of three different tasks depending on whether a variable x has the value 1, 2, or 3. Notice the subtle difference between these two pieces of code:
#  first method - execution stops once the correct choice is found
if x == 1:
    z = 1
    print 'Setting z to 1'
elif x == 2:
    y = 2
    print 'Setting y to 2'
elif x == 3:
    w = 3
    print 'Setting w to 3'

# second method - all three tests are done regardless of x's value
if x == 1:
    z = 1
    print 'Setting z to 1'
if x == 2:
    y = 2
    print 'Setting y to 2'
if x == 3:
    w = 3
    print 'Setting w to 3'
Since x can only have one value, there's no need to test its value once the appropriate task is performed.


next up previous contents
Next: for loops Up: Programming Previous: Truth, Falsehood and Logical   Contents
Phil Spector 2003-11-12