Computers were invented initially for the purpose of performing normal calculations quickly and repeatedly. There are two simple ways to think of repeating a task: either one sets out to repeat the task on each element of some list, or one performs a task repeatedly so long as some condition is met. These correspond to the two fundamental methods of iteration available to Python programmers: for loops and while loops.
SubsectionA.4.1For loops
Consider the mathematical problem of finding the equation of a straight line containing both of the points \((x_1,y_1)\) and \((x_2,y_2)\text{.}\) It takes just a moment to write down the formula \(x=x_1\text{,}\)\(y=y_1\text{,}\) or
and plug in the respective constants. However it becomes more costly in terms of time if the same calculation needs to be carried out for several hundred pairs of points! In fact, even reading in several hundred pairs of points from a file in order to do such a calculation is tedious.
For loops are the ideal programming construction to use when a repetitive task or procedure must be performed on a predetermined set of inputs or a predetermined number of times. Specifically, Python will allow a for loop to repeat over any container which is an iterable, like a tuple or list.
TechnologyA.4.1.for loops.
To perform a task repeatedly while a variable loop_var successively takes each value in a list, tuple, or other iterable my_container, we use the for loop block structure, as follows:
for loop_var in my_container:
# Print the value of loop_var
print(loop_var)
# Perform a task
# Perform another task
# And so on
ListingA.4.2.A typical use of the for block structure
This is shown as part of a module rather than input to the Python console to emphasize the block structure. In Python, blocks of code are indicated by the level of indentation of the code. It is normal for Python editors to insert 2 or 4 spaces when the tab key on the keyboard is pressed, rather than the special tab character represented in Python by '\t'. This is an important behavior to the Python interpreter, and provides a very good reason to use a Python editor or IDE instead of a text editor for writing Python code!
The colon : at the end of the first line indicates to Python that the interpreter should expect an indented block starting on the next line.
The hash marks appearing in the above technology description are an important code-writing tool.
TechnologyA.4.3.Comments.
A comment is any code which is not evaluated by Python. The special symbol # in Python denotes the start of a comment, and so whenever # occurs outside of a string it begins a comment. Comments are used to make a note for someone reading the code.
The Python implementation of for loops is very practical. Given a finite mathematical sequence of elements \((a_i: i\in\set{0,1,2,\dotsc,n-1})\) the important values are the values \(a_i\text{,}\) not the values of \(i\)itself! This is one way Python differs from the implementation by more earlier programming languages.
RemarkA.4.4.For loops in other languages.
In many other languages the normal behavior is different, and for loops can only take successive integer values. For instance, in C++ the following code starts the integer \(i\) at the value 0 and so long as \(i\lt 20\) prints the value of \(i\) (that’s the cout << i; part) and then increases the value of \(i\) by one (that’s the i++) part.
for (int i = 0; i < 20; i++ ){
cout << i;
}
ListingA.4.5.An example of a for loop in C++
This is the traditional use of a for loop: the looping variable serves as an index variable (like a subscript variable) and is changed until a certain range condition is met. This behavior is still available in Python, using the range function. To produce the same output as the above C++ code in Python is uncomplicated.
for i in range(20):
print(i)
ListingA.4.6.The same for loop as Listing A.4.5 reproduced in Python
The range function as remarked above is an iterable, since it can be iterated over by a for loop. The several ways to call the range function and its output in each case are important.
TechnologyA.4.7.The range function.
The output of a range function is not a list or a tuple, though it acts like one. It is a special “range object”, but can be easily converted to a list or tuple by type casting. Here are the basic uses of the range function, assuming my_list, m, n, and k are defined.
TableA.4.8.The uses of the range function in Python
Command
Output
range(m)
The indices of a container of length \(m\)
range(m,n)
The indices sliced by my_list[m:n]
range(m,n,k)
The indices sliced by my_list[m:n:k]
As an example, the following would be produced at the Python console. The fourth input shows that the range object output on its own is not a list.
The other type of common iteration is to repeatedly perform a task so long as some condition is true, which is a sort of transition between talking about iteration and conditional statements!
TechnologyA.4.10.while loops.
A while block depends for its execution on a conditioning expression, and the block executes repeatedly so long as the expression evaluates to True. Here is a short example of a while loop which will terminate after a few iterations.
Note that the parentheses on the second line are unnecessary, but they help a reader recognize the condition for the loop. Any statement which can evaluate to either True or False can appear as the condition of a while loop.
The following example of a while loop is called an infinite loop, because it will never terminate. Generally speaking, a program stuck in an infinite loop in Python can be terminated by pressing Ctrl-C, which triggers a KeyboardInterrupt.
while True:
pass
ListingA.4.12.The canonical example of an infinite while loop
The pass statement is a do-nothing statement which is syntactically valid to be a do-nothing statement. This means an indented block containing a pass statement will do nothing. This is especially useful when first learning programming.
All of these concepts will combine in the next section as we move towards building useful programs in functions.