Statements: Loops

Introduction

It is useful to be able to use control structures to decide which block of statements we will execute based on conditions, however, sometimes we need to control the flow of execution in a different way. Often we come across a situation where we need the same block of code to run repeatedly while a certain condition exists. In this situation, we make use a another kind of statement or structure called a loop.


Loops

There are a number of specific looping structures we can make use of. We'll take a look at some of the common ones: For, While and Range. The specific structure we choose will depend on information available to us in the code at the point of execution, and the type of control we need over the behaviour of the loop.

For Loop

A For loop is useful for iterating over a set number of items in a collection in sequence. But how do we know when to make use of the For loop rather than the While or Range looping structures? Well, if the following criteria are met, we will use the for loop:

We use the for loop when

  1. We can determine the number of times the statement block should repeat.
  2. We want to loop sequentially over a the entire list of objects.

The syntax for the for loop is

for  in :
    # This is the code that is repeated

Some explanation is required for the above syntax. Firstly, the * is a composite data type (remember we discussed this in the section on Data Types) such as an Array. The * is going to hold the value of the specific item in the collection which we are considering at each iteration of the loop.

Let's take a look at an example of a for loop, and then we will discuss the syntax further. Open up the Python interactive interpreter and give the following code a try:

arr = ['Apple', 'Banana', 'Cherry', 'Date']
for fruit in arr:
    print fruit

[Output: Apple
Banana
Cherry
Date]

In the above example, the collection we are looping through is an array of strings held in the variable arr. Our iterator variable is fruit. This means, that within the indented block of code which is repeated, we won't be referencing the collection (arr), but rather, we will be working with fruit which will be the specific string in the collection we are considering at each iteration. So in this example, the first time the loop runs, fruit will hold the string "Apple", the second time the loop runs, fruit will contain the string "Banana" and so on.

While Loop

A while loop provides a binary arithmetic expression as the looping condition. While the expression resolves to true, the loop will continue running. This is useful in situations where you might not know exactly how many times you need to loop. For example, when you are reading lines from a text file, or reading user input, etc...

The syntax for a while loop is as follows:

while :
    # This is the code that loops

The **** in the syntax above is similar to the conditions we considered in the conditional statements from the previous section. Let's take a look at some examples of while loops:

Example 1: Reading User Input until keyword is entered

print "Enter a message to be echoed. Exit by typing 'exit'"
input_str = ""
while input_str != "exit":
    input_str = raw_input("String to echo: ")
    print "Echoing, %s" % (input_str)

In the above code, we initialize the input_str string variable with a blank string. Then, as long as the input_str variable does not equal to "exit" we continue to ask the user for messages to echo back. This will continue until they enter "exit" which will then cause the loop to stop running, as the condition, input_str != "exit" will resolve to false.

Example 2: Infinite Loop

while true:
    print "I can't stop running!"

In this example, the condition is the tautology "true", which will always be true, thus the loop will always continue to run until the program is forcibly halted. This might seem a bizarre scenario to beginners, but this is actually quite a common practice in GUI (Graphical User Interface) and Daemon applications.

Example 3: Reading lines from a text file

fh = open("some_file.txt", "r")
line = fh.readline()
while line:
    # Do something with the line, then read the next line
    line = fh.readline()

In this example, we might be dealing with a very large text file, and we want to consider each line before moving onto the next, without necessarily knowing how big the text file is (or how many lines it contains). So, we read a line, until no line is returned; in which case "while line:" will result in a false condition, and the loop will stop running.

Range

The final loop structure we will consider is the Range loop. This is not a looping structure itself, but is used in conjunction with a for loop to provide more control. This technique affords more control over the subset and iteration step of each loop cycle. So, we might have a list of 100 items, and we want to loop through only items 10 to 80, and only consider every second item.

The syntax for the range function:

range(start, end, iteration_step)

To explore this, open up your Python interactive interpreter and give it a try with various values for start, end and iteration_step.

As an example:

range(10, 90, 2)
[Output: [10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88]]

So here, we are generating an array of values from 10 to 90, and only consider every second item.

Let's now use this in conjunction with the for loop.

for i range(10, 20, 3):
    print i
[Output: 10
13
16
19]

Loop Controls

To end off with, let us briefly look at some useful instructions to control the looping structure from within the looping instruction set.

Break

If we have some logic inside the loop that decides we need to stop looping, we can call the "break" command to then exit the loop.

Example:

arr = ['Apple', 'Banana', 'Cherry', 'Date']
for fruit in arr:
    print fruit
    if fruit == "Banana":
        break

[Output: 'Apple'
Banana]

Continue

Sometimes, we need to stop execution of the current loop iteration, but not exit the loop, just move on to the next iteration. To do this, we use the continue command.

Example

arr = ['Apple', 'Banana', 'Cherry', 'Date']
for fruit in arr:
    if fruit == "Banana":
        continue
    print fruit

[Output: 'Apple'
Cherry
Date]

In the above example, if the current fruit is "Banana", then don't print it out, just move onto the next iteration in the loop.


Exercises

  1. What kind of loop would we use if we wanted to code a guessing game, where the program would count the number of times the user took to guess a number correctly?
  2. Write the code to implement the program described above.

Continue to next section


Comments

comments powered by Disqus