Table of Contents

11.1. Repetitions
11.2. The for loop
11.3. The while loop
11.4. Comparison of for and while loops
11.5. Range and Xrange objects
11.6. The map function
11.7. List comprehensions

11.1. Repetitions

As you have seen in Section 3.4, sometimes you need to do the same thing several times with different data. Whereas humans make often errors during a repetitive procedure, computers execute repetitive tasks very well. One possibility to write repetitions is to repeat the code as often as needed, but this is neither elegant nor readable, and above all you cannot do this if the number of repetition times is not constant or is not known beforehand.

Because repetitions are common programming tasks, high level programming languages provide special structures and statements for this purpose. Python has two of them: for and while. Let us see the for statement first.