Chapter 6 Loop Statement

6.2 For Loop

The for statement is a second looping statement. It can be used to iterate through a container object. The syntax of the for statement is shown in Fig. 6.3, which begins with a line that consists of the for keyword, followed by an identifier, and then the in keyword, and then a container object, and finally a colon.

Fig. 6.3 The for statement

Fig. 6.3 The for statement

After the for line is an indented statement block, which is executed repeatedly, once for each element in the collection object. In each iteration, the current element of the collection is assigned to the identifier after the for keyword, which serves as the loop variable. For example, the following code iterates through a collection generaged by range function, printing out each element from 0 to 9:

In the example above, the for statement consists of two lines, the first being the for line with the loop variable being defined as x, and the second line being an indented statement block that consists of a single statement. When executed, the for statement iterates through all elements of the collection, assigning the current element to the identifier x at each iteration, before executing the indented statement block, or loop body. As a result, the dynamic execution sequence of the example above is:

x=0
print (x)
x=1
print (x)
x=2
print (x)
.....
x=9
print (x)

An equivalent loop using the while statement is:

In the example above, the variable i is used as the loop variable. It iterates through the values 0, 1, … , len(t). At each iteration, a corresponding element t[i] is taken from the container t, and assigned to the variable x. This type of iteration through a container object is called traversal. Compared with the while loop, the for loop is more convenient for performing collection traversal. Since using a for statement, the additional loop variable i is unnecessary. Container objects that can be iterated through using a for loop are also called iterable objects.

Check your understanding

Note

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

© Copyright 2024 GS Ng.

Next Section - 6.3 Branching Nested in a Loop