Whenever we need to do something over and over again in a program, loops allow us to repeat those steps without having to type each one separately.
The for
Loop
A for loop in Python iterates over a list of items, or repeats once for each item in a list -like the numbers 1 through 100, or 0 through 9. We want our loop to run four times - once for each circle - so we need to set up a list of four numbers.
The built-in function range() allows us to easily create lists of numbers. The simplest command to construct a range of n num- bers is range(n)
; this command will let us build a list of n numbers from 0 to n-1
(from zero to one less than our number n).
The while
Loop
Instead of iterating over a predefined list of values, as the for loop does, a while loop can check for a condition or situation and decide whether to loop again or end the loop.
The condition is usually a Boolean expression, or true/false
test. One everyday example of a while loop is eating and drinking. While you are hungry, you eat.
The Spiral
Spiral Goes Viral
Summary
At this point, you should be able to do the following:
- Create your own for loops to repeat a set of instructions a cer- tain number of times.
- Use the range() function to generate lists of values to control your for loops.
- Create empty lists and add to lists using the append() function.
- Create your own while loops to repeat while a condition is True or until the condition is False.
- Explain how each type of loop works and how you code it in Python.
- Give examples of situations in which you would use each type of loop.
- Design and modify programs that use nested loops.