Flow control—iteration

Objectives

  • Know how to use for and while statements for repeated execution.

In this lesson, we will look more at how we can control the flow of our programs. We will investigate how we can execute statements multiple times, using the for and while commands in Python.

Once again, we will consider an example situation involving an experiment in which multiple trials are presented. This experiment is extremely simple, and only consists of the trial number being printed to the screen.

If we have five trials, we could achieve this by writing:

print 1
print 2
print 3
print 4
print 5
1
2
3
4
5

Obviously, this is going to get very tedious and error-prone, particularly if there are lots of trials or the code for each trial is complex. Since it is likely that both these factors will be true for any real experiment that we would run, we need to find a way to automate these repeated tasks.

for loops

We can do so using a for loop. This construct takes a collection of data and loops over the items one at a time. For example:

trials = range(1, 6)

for trial in trials:
    print trial
1
2
3
4
5

As you can see, this produces the same outcome as the manual way. Let’s unpack how it works.

  • First, we used the range function to generate a list of the integers 1 through 5.

  • We then define our loop:

    • We start by using for, which is a special Python keyword.
    • We then specify a variable name—as usual, this can be close to anything we like, and here we call it trial.
    • We then give another special Python keyword, in, followed by our list, followed by a colon (:).
    • This sequence can be read as “loop over the items in the list called trials, each time calling the item trial”.
  • We then define what happens on each pass through the loop:

    • We use indentation again to indicate nested program structure; everything that is indented ‘under’ the for line is executed once for every item in the trials list.
    • On the first pass through, the variable trial is set to the number 1, because that is the first item in the trials list, and the print statement outputs it to the screen.
    • On the second pass through, the same process occurs except the variable trial is now set to the number 2, the second item in the trials list.
    • This process continues until all the items in the trials list have been used.

while loops

The for loop construct is very useful, but is sometimes not ideal because we have to specify exactly how many iterations we want to perform (how many items in the list). Sometimes we don’t know how many iterations we want to run—we only know that we want to continue iterating until some desired state is reached.

We can reproduce the same functionality as our for loop using a while loop as follows:

trial = 1

while trial < 6:

    print trial

    trial = trial + 1
1
2
3
4
5

Let’s consider how this worked:

  • First, we established an initial condition by creating the variable trial and giving it a value of 1.
  • We then indicated that we would like to define a while loop.
  • The expression immediately following the while keyword establishes the conditions under which the loop should continue. As long as the expression evaluates to True (“while” the expression evaluates to True), the “body” of the loop is repeatedly executed. Here, we tell Python to continue executing the loop while the value in the variable trial is less than 6.
  • We then include a colon (:) to indicate that we are ready to specify the body of the loop.
  • We then indent, to indicate that we are within the body of the loop, and specify the command that we want to occur on each pass through the loop (printing the contents of the variable trial).
  • The final, and critical, step is to increment the value in the variable trial. That way, the loop will terminate once the value of trial gets beyond 5.

Tip

A potential caution with while loops is that is easy to produce an “infinite loop” by having a test that will never evaluate to False—meaning your program would run forever!

Let’s look at another example. Say a trial involves presenting a dynamic pattern that the participant needs to make a judgement about. We don’t know precisely when they will make this judgement, because it is up to the participant. This is a good situation for using a while loop.

To simulate a participant in our example, we will draw a random number on each iteration of the loop. If this random number is above 0.9, we take that as akin to a participant response and we end the loop. For example:

import random

responded = False

while not responded:

    print "Looping!"

    if random.random() > 0.9:
        responded = True
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!

Let’s work through what is happening in the above code.

  • First, we imported the extra functionality available in the random package.
  • Next, we defined a variable that is a boolean indicating whether the participant has responded yet; our initial state is that they have not responded.
  • We then start our loop by using the special Python keyword while, followed by something that evaluates to a boolean—in this case, we are testing whether participants have not yet responded. As long as this boolean evaluates to True, the code that is indented beneath the while line will repeatedly execute.
  • Because it starts out as True (because we set responded to False, and not False is True), we begin to execute the indented code.
  • First, we print out a string just to show that we are executing this particular line of code.
  • Next, we generate a random number between 0 and 1 and test if it is greater than 0.9.
  • If it is, we set the variable responded to the value of True.
  • We then go back up to our while loop definition, and evaluate the boolean test again.
  • If it continues to evaluate to True, we go and execute the code again.
  • However, if it now evaluates to False, then we don’t execute the code and we move on and finish the program.