Chapter 8. Looping

The for and while Statements; The break , continue and pass Statements; The assert Statement

The elements of Python we've seen so far give us some powerful capabilities. We can write programs that implement a wide variety of requirements. State change is not always as simple as the examples we've seen in Chapter 6, Variables, Assignment and Input . When we run a script, all of the statements are executed unconditionally. Our programs can't handle alternatives or conditions. The other thing we can't do is write programs which do their processing “for all” pieces of data. For example, when we compute an average, we compute a sum for all of the values.

Python provides iteration (sometimes called looping) similar to other programming languages. In the section called “Iterative Processing: For All and There Exists” we'll describe the for and while statements. This is followed by some of the most interesting and challenging short exercises in this book. We'll add some iteration control in the section called “More Iteration Control: break and continue , describing the break and continue statements. We'll conclude this chapter with a digression on the correct ways to develop iterative and conditional statements in the section called “A Digression”.

Iterative Processing: For All and There Exists

There are two common qualifiers used for logical conditions. These are sometimes called the universal and existential qualifiers. We can call the "for all" and "there exists". We can also call them the "all" and "any" qualifiers.

A program may involve a state that is best described as a “for all” state, where a number of repetitions of some task are required. For example, if we were to write a program to simulate 100 rolls of two dice, the terminating condition for our program would be that we had done the simulation for all 100 rolls.

Similary, we may have a condition that looks for existence of a single example. We might want to know if a file contains a line with "ERROR" in it. In this case, we want to write a program with a terminating condition would be that there exists an error line in the log file.

It turns out that All and Any are logical inverses. We can always rework a "for any" condition to be a "for all" condition. A program that determines if there exists an error line is the same as a program that determines that all lines are not error lines.

Any time we have a “for all” or "for any" condition, we have an iteration: we will be iterating through the set of values, evaluating the condition. We have a choice of two Python statements for expressing this iteration. One is the for statement and the other is the while statement.