Repetition in Python: Counting Loops

Features of programming languages are provided because the designers know they are useful. The while loop is obviously useful, and is the only kind of loop required to implement a program. However, loops that involve counting a certain number of iterations are common, and adding syntax is valuable. Some­times a loop that executes, for example, ten times, or a loop that iterates N times for some variable N, is needed. In Python, this is called a for loop.

In some languages, a for loop involves a special syntax, but in Python, it involves a new type (a class of types, really): a tuple. Here is an example of a for loop:

for i in (1,2,3,4,5): print i

This code prints the numbers 1 2 3 4 5 each on a separate line. The variable i takes on each of the values in the collection provided in parentheses and the loop executes once for each value of i. The collection (1,2,3,4,5) is called a tuple, and can contain any Python objects in any order. It’s basically just a set of objects. The following are legal tuples:

(3,6, 9, 12)

(2.1, 3.5, 9.1, 0, 12)

(“green”, “yellow”, “red”)

(“red”, 3, 4.5, 2, “blue”, i) #where i is a variable

with a value

The for loop has the loop control variable (in the case above it is i) take on each of the values in the tuple, in left to right order, then executes the connected suite. The loop therefore executes the same number of times as there are elements in the tuple.

Sometimes it may be necessary to have the loop execute a great many times. If the loop was to execute a million times, it would be difficult to require a pro­gram to list a million integers in a tuple. Python provides a function to make this more convenient: range(). It returns a tuple that consists of all of the integers between the two parameters it is given, including the lower end point.

range (1,10) is (1,2,3,4,5,6,7,8,9)

range (-1, 2) is (-1,  0, 1)

range (-1, -3) is not a proper range.

range (1,  1000000) if the set of all integers

from 1 to 9999999

Ranges involving strings are not allowed, although tuples with strings in them are allowed. The original example for loop can now be written:

for i in range(1,6): print i

and the loop that is to execute a million times could be specified as

for i in (0,     1000000):

print i

This code prints the integers from 0 to 999999. If range() is passed only a single argument, then the range is assumed to start at 0; this means that range (0,10) and range (10) are the same.


Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *