4. Control flow, or, how Python knows what happens when (Python 2)


This section covers how to get the Python interpreter to execute commands, or not to execute them, in the order you want it to. As was stated in Section 1, in the simplest case, Python merely runs through the source file executing each command one after another, from top to bottom.

4.1. Blocks and whitespace in Python

In most programming languages, tabs, new lines and spaces (so-called 'whitespace') have no meaning to the computer, and are merely added to make the code more legible to the programmer. In Python, whitespace is 'syntactically significant'. To be specific:

a) a command written on one line can't just run over to the next line (unless you add a backslash: \ at the end of the line). For example:
  • print
    "Hello, World"
will not work, but:
  • print "Hello, World!"
and
  • print \
    "Hello, World!"
will.

b) Lines of code with different levels of indentation are treated differently. In other words, if you have more whitespace characters at the front of one line than another, Python thinks of it as part of a different 'block':
  • print "This is part of one block!"
    print "This is a different block!"
    print "Back to the first block."
Blocks are key to using IF statements and loops.

Although you can use both spaces and tabs to indent your code, it is recommended that you pick one and only use that one (since one tab looks like four spaces to you, but to Python, one tab = indentation level 1, and four spaces = indentation level 4).


4.2. The IF statement

This is how you get Python to do interesting things. An IF statement is basically a function that takes something that can be evaluated as a Boolean argument and, if true, executes the block following the statement:
  • a = 2
    if ( a > 1):
    print "Yes, ", a, " is greater than 1!"
Note the key elements:
a) a Boolean comparison inside the parentheses
b) a colon after the if (telling it to apply the statement to the entire following block
c) a block, delimited by a higher indentation level.

You can append 'elif' statements to an if statement, which also take a Boolean argument, and only attempt to evaluate if the initial if statement failed:
  • a = 1
    if ( a < 1 ):
    print "Yes, ", a, " is greater than 1!"
    elif( a == 1 ):
    print "Yes, ", a, " is equal to 1!"
After any if and elif statements, you can add an 'else' clause, which will execute only when the if clause and all elifs failed:
  • a = 9
    if ( a < 1 ):
    print "Yes, ", a, " is greater than 1!"
    elif( a == 1 ):
    print "Yes, ", a, " is equal to 1!"
    else:
    print a, " is less than 1!"
The colon and indentation can be omitted if you are only executing one command, by putting everything on one line:
  • a = 2
    if (a == 2) print "The value is two."

4.3. Loops

Loops are how you get Python to repeat code a number of times without having to repeat it forever. There are two types of loop in python: while and for.

The while loop takes a Boolean argument, like an if statement, and executes the subsequent block as long as the argument evaluates as true. For example, the following code will print the numbers 1 through 9:
  • a = 1
    while a < 10:
    print a
    a = a+1
You must be cautious to make sure that this sort of loop will end! In general it is important to be careful about termination conditions for loops. What is the final value of the variable a in the above code? Make sure you understand why the loop above only gets to the number 9.

The for loop is probably the loop you'll use most often. It is rather different from for loops in other languages. You can iterate over any sort of list. You first specify an arbitrary name for one item of the list, and then the list:
  • list = [0, 1, 2, 3]
    for item in list:
    print item
If, as is frequent, you need to iterate over a list of numbers, the range function is useful. This function produces an array with the specified number sequence in it.
  • for number in range(3):
    print number # prints 0, then 1, then 2, then 3
The function can take several other parameters. If a second parameter is added, the two numbers are treated as the starting point and end point:
  • for number in range (1,3):
    print number # prints 1,2,3
If a third parameter is added, this number is treated as the increment between successive numbers. This number can be positive or negative:
  • for number in range (2,-2,-2)
    print number # prints 2, 0, -2
Up to Index
Previous: 3. Basic IO functions | Next: 5. Data types





The compwiki.physics.utoronto.ca site content is Copyright 2009, 2010, 2011, 2012 Department of Physics, University of Toronto.