2.2. Control Constructs

Keeping with the ‘keep it simple‘ philosophy of Python, there are three primary control constructs (aside from functions and classes) that determine the sequence of instructions executed by a Python program. (The if Statement, The while Loop, The for Loop)

2.2.1. The if Statement

The Python if statement is pretty much the same as it is with other programming languages. It is the primary selection statement that provides the semantics for determining conditional execution of blocks of code.

The simplest form works to determine conditional execution of a single block of code:

if x < 5:
    statement_1
    statement_2
    ...

Add the else clause to pick between two code blocks:

if x < 5:
    alt_statement_a1
    alt_statement_a2
    ...
else:
    alt_statement_b1
    alt_statement_b2
    ...

The elif clause lets us pick from several code blocks to execute:

if x < 5:
    alt_statement_a1
    alt_statement_a2
    ...
elif x < 10:
    # 5 <= x < 10
    alt_statement_b1
    alt_statement_b2
    ...
elif x < 15:
    # 10 <= x < 15
    alt_statement_c1
    alt_statement_c2
    ...
else:
    # x >= 15
    alt_statement_d1
    alt_statement_d2
    ...

2.2.2. The while Loop

The while loop is the primary looping construct to use when the number executions of the loop depend on the data being processed or how the user interacts with our program. Python while loops work the same as they do with other languages.

while something_is_true:
    do_this_code_block

2.2.3. break and continue

Sometimes we have to execute part of the code in a loop before we know that we are are ready to exit the loop, or that we want to skip the rest of the code block and process the next value in the sequence (if one exists). This is where break and continue come to the rescue.

break

The break statement will get us out of the last loop we entered.

continue

The continue statement will skip the remainder of the code block so that the loop condition may be re-evaluated and possibly start the loop over again or stop executing the loop.

2.2.3.1. Infinite loops

Sometimes we want to loop forever, or until told to stop. This is a case where, you might actually want to write an infinite loop, usually with a break somewhere in the loop. Remember that any value that is not one of False, 0 or None evaluates to True. Thus we usually see infinite loops expressed as either:

while 1:
    ...
    if exit_condition:
        ...
        break
    ...

or:

while True:
    ...
    if exit_condition:
        ...
        break
    ...

2.2.3.2. Nested Loops

It is also quite common to have nested loops. For these loops, we often need a mechanism to get out of just the inner loop or out of booth loops on certain conditions.

Using a boolean variable as the test condition for one of the loops, usually the outer loop, seems to work most of the time for these situations:

more = True
while more:
     ...
     while True: # your inner loop
         ...
         if a_conditon:
             # exit just the inner loop
             ...
             break
         if another_condition:
             # exit both inner and outer loops
             ...
             more = False
             break

2.2.4. The for Loop

See also

for loops are also discussed in the section on sequences of data: see Sequences and the for Loop.

As with other programming languages, the for loop in Python is considered a definite, or counted loop because unless a break statement is executed, the number of times that the loop will execute is known. [1] However, the for loop does not look or work the same way in all languages. The Python for loop is similar the same in Unix shell, perl and other scripting programming languages, which is quite different than the for in Java or C/C++. A Python for loop iterates over the elements in a sequence rather than using three operators (initialize, test and increment).

>>> a = [1, 2]:
>>> for i in a:
...     print i
...
1
2

Iterating over a data sequence is the most common usage of for loops in any programming language. For those times when you just want a sequence of numbers, the built-in range() function comes in handy. Note that range() may be called with one, two or three parameters. If one parameter is supplied, it is assumed to be the stop value, which means that it starts at 0, as do the indices of lists and tuples. When two parameters are supplied, they are assumed to be for start and stop.

Here are some examples of using for loops with the range() function:

>>> for i in range(2):
...     print i
...
0
1
>>> x = range(1,3)
>>> for i in x:
...     print i
...
1
2

2.2.4.1. range built-in function

range([start], stop[, step])

Return a list of integers.

Parameters:
  • start (integer) – first value in the list
  • stop (integer) – one greater than the last value in the list
  • step (integer) – the difference between consecutive values in the list

Note that if stop is the only supplied parameter, it is also the length of the returned list.

A couple examples of range():

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(2,5)
[2, 3, 4]
>>> range(1,5,2)
[1, 3]
>>> range(0,6,2)
[0, 2, 4]

Footnotes

[1]For some iterable objects, it is not quite so obvious how many items are contained in the sequence. However, it should be determinate. One example of a not-so-obvious case is the generator function os.walk(). From the os module. This function takes a directory name and returns an item for the directory and every sub-directory under the directory parameter.