Python Flow Control


In a previous notebook, we covered the basic Python concepts required to begin writing legal Python code. In this notebook, we will introduce additional fundamental concepts that form the basis of many Python programs: conditional statements, iterative looping, and (optionally) comprehensions.


Python Flow Control

The Python programming language provides standard techniques for controlling a programs flow, both in terms of supporting conditional statements, where different code blocks are evaluated depending on the value of a specific statement, to a variety of iterative loop statements that enable repeated evaluation of a code block until some condition is met. As an example, a loop could iterate until all items in a sequence have been processed.

Conditional Statements

Python supports conditional execution of code blocks by using if conditional branching statements. Multiple branches are supported by using one or more elif commands, which is shorthand for else if, after the initial if statement. An else statement can be used to handle any results that are not met by previous conditional statements. The code blocks are initiated by a colon character following and indented four spaces, as demonstrated in the following sample code:

if (x > 10):
    print("x is large")
elif (x > 5):
    print("x is medium")
else:
    print("x is small")

Depending on the value of the variable x, the first, second, or third print statement will be executed. if control statements can be nested if required by the algorithmic logic, but doing so requires being extremely careful to maintain proper indentation. Nested conditional statements are demonstrated in the following sample code:

if (x > 10):
    if (y > 10):
        print("x and y are large")
    else:
        print("x is large, but y is not")  
elif (x > 5):
    if (y > 10):
        print("x is medium but y is large")
else:
    if (y > 10):
        print("x is small and y is large")
    elif (y > 5):
        print("x is small but y is medium")
    else:
        print("x and y are small")

Student Exercise

The Code cell below contains this last conditional statement. Provide your own initial values for x and y, and before executing the Code cell, determine what output will be displayed. Now run the code cell Was your expectation correct? Try different values for x and y and repeat this process, and (optionally) try changing the conditional statements.


In [1]:
# Change the values for x and y and see how the output changes

x = 10
y = 10

if (x > 10):
    if (y > 10):
        print("x and y are large")
    else:
        print("x is large, but y is not")  
elif (x > 5):
    if (y > 10):
        print("x is medium but y is large")
else:
    if (y > 10):
        print("x is small and y is large")
    elif (y > 5):
        print("x is small but y is medium")
    else:
        print("x and y are small")

Python Iterations and Loop Statements

Python supports several loop statements, but the most commonly used by far is the for loop, which is used to iterate through a sequence like a list, tuple, or dictionary. The indented code block that follows the colon character at the end of the for statement is executed for each loop. The following loops demonstrate the use of the for loop to iterate through the items in different Python data structures:

list:

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for item in data:
    x = 10**int(item)
    print("10**{0} = {1}".format(item, x))

tuple:

data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

for item in data:
    x = 10 * int(item)
    print("10 * {0} = {1}".format(item, x))

string:

text = "The brown dog jumped over the quick fox!"

for c in text:
    print("{0}".format(c))

dict:

d = {'1': 1, '2': "two", '3': (1, 2, 3)}

for k, v in d.items():
    print("d[{0}] = {1}".format(k, v))

In those instances when you simply want to loop n times, you use the range(n) command to create an iterable sequence that can be used with the for command:

for x in range(10):
    print("Iteration: {0}".format(x))

On occasion, you will want to iterate through an ordered sequence using both the ordinal number of the item and the item itself. This functionality is provided by the enumerate Python command, which returns both the item and its ordinal number in the sequence as demonstrated by the following code example:

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for index, item in enumerate(data):
    x = index**int(item)
    print("{0}**{1} = {2}".format(index, item, x))

You should use the following code cells to experiment with iterations in Python by using the for loop.


In [2]:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for index, item in enumerate(data):
    x = index**int(item)
    print("{0}**{1} = {2}".format(index, item, x))

The other type of loop in Python is the while loop, which executes a code block until a condition has been met. The code block is indented following the colon character at the end of the while statements. Syntactically, the while statement takes the following form:

while (condition):
    one or more statements

A while loop can often be rewritten more succinctly as a for loop that iterates through some sequence. One exception to this is when code blocks should be executed, for example, to perform some operation until a condition that depends on the result of the code block itself.

value = 1
while value < 1E6:
    value *= 10
    print("Current value = {0}".format(value))

Both for and while loops can be nested, and include conditional statements as well. There are four other commands that can be used with for and while loops: else, break, continue, and pass.

else:

The for and while loops both support an optional else clause that is executed immediately after the loop exits. In the case of a for loop, this occurs when the items in the sequence have been exhausted, while for the while loop this occurs when the condition has become False.

break:

The break statement is generally used in nested loops, terminating the nearest enclosing loop and skipping any optional else clauses associated with the broken loop. For example, the break command exits out of the inner for loop in the following code segment:

for i in range(4):
    for j in range(3):
       if (j > 2):
           break
       else:
           print("{0} inner loop iteration.".format(j))

    print("{0} outer loop iteration.".format(i))

continue:

The continue statement is generally used in nested loops, and skips the rest of the current code block and continues on with the next iteration of the nearest enclosing loop. For example, the continue command continues with the next iteration of the inner for loop in the following code segment:

for i in range(4):
    for j in range(3):
       if (j > 1) and (j < 4):
           continue
       else:
           print("{0} inner loop iteration.".format(j))

    print("{0} outer loop iteration.".format(i))

pass:

The pass statement does nothing and is a simple placeholder that is used in place of a code block when no action is required. Presumably this is because the work is done in the iteration process itself. This can occur in a while loop when the test condition is a function call, and a pass statement is used for the code block since no actual computations are required inside the loop itself. This statement can be used within a conditional statement or loop construct.


In [3]:
for i in range(4):
    for j in range(3):
       if (j > 1) and (j < 4):
           continue
       else:
           print("{0} inner loop iteration.".format(j))
    
    print("{0} outer loop iteration.".format(i))

Student Exercise

In the empty Code cell below, create a list that contains the odd integers from 1 to 19, iterate over each number in this list, and print one number from the list per line of output. This can be done using a for loop with a list created by using the range function.


In [ ]:
 

Optional: Comprehensions

Since the list and dictionary are such fundamental components of many Python programs, there exists a shorthand notation for quickly building and using these data structures that are known as comprehensions. The formalism for either a list comprehension or a dictionary comprehension, is to simply place Python code inside the respective characters that are used to create a new list or dictionary, respectively. This code generally involves an iterative process that uses a for loop, and can also include an optional conditional statement. For example, the following code creates a list with elements that are the squared value of the integers from zero to nine:

data = [x**2 for x in range(10)]

After this line of code, data is equal to the list [0, 1, 4, 9, 16, 25, 36, 49, 64, 81].

We can apply a conditional statement to this list comprehension to only retain the squares that are even numbers:

data = [x**2 for x in range(10) if not (x % 2)]

After this line of code, data is equal to the list [0, 4, 16, 36, 64].

We can create more complex list comprehensions:

data = [(x, x**2) for x in range(4)]

which produces a list of tuples: [(0, 0), (1, 1), (2, 4), (3, 9)].

We can also easily create dictionary comprehensions by using the curly braces to properly create a new dictionary:

data = {x: x**2 for x in range(3, 7)}

which creates a new dictionary called data that contains the following items: {3: 9, 4: 16, 5: 25, 6: 36}. More complex dictionaries can also be created with dictionary comprehensions, as shown in this example:

data = {x: (x, x**2, x**3) for x in range(3, 7)}

Comprehensions are generally faster than traditional list or dictionary operations, and support the application of functions to create the list or dictionary items. Comprehensions can also be nested as required. Python3 also supports set comprehensions.


Ancillary Information

The following links are to additional documentation that you might find helpful in learning this material. Reading these web-accessible documents is completely optional.

  1. The official Python documentation for control flow statements
  2. The book A Byte of Python includes an introduction to control statements.
  3. The book Think Python includes a discussion on conditional statements and loops.
  4. The book Dive into Python includes a nice discussion on comprehensions.

© 2017: Robert J. Brunner at the University of Illinois.

This notebook is released under the Creative Commons license CC BY-NC-SA 4.0. Any reproduction, adaptation, distribution, dissemination or making available of this notebook for commercial use is not allowed unless authorized in writing by the copyright holder.