What is a loop?
A loop is a programming construct that makes a section of code execute more than once. There are (broadly) two types of loop: for loops and while loops.
How should I understand loops?
Like many aspects of programming, the best way to understand a loop is by making an analogy to the real world. Here are some real world loops:
- Dealing a hand of poker (or some other card game). You keep dealing cards until each player has 5.
- Icing cup cakes. If you've just baked 30 cup cakes, you need to apply the same icing procedure to each one.
- Repairing a car that won't start. While the enginer won't start, find a fault with it and and fix it.
- Working in a supermarket. Keep serving customers until the end of your shift.
There are a number of indications in these descriptions that give us a clue that these activites are loops:
- Repetition of the same action.
- Use of the words "while" or "until".
- A condition, that tells us when we should stop doing a certain action.
To enable you to translate a real world description of a loop into syntax a computer will understand, you need to practise phrasing loops in the right way. This takes practise, and is best accomplished with examples.
What types of loop are there?
Most languages have several different types of loop which are used under different circumstances. Python has both a while loop and a for loop. Although different types of loop can be more convenient in different problems, all loops are effectively equivalent - the results of a for loop can be achieved using a while loop and vice versa.
We will start working with while loops, since they capture the important features of a loop most clearly.
The parts of a loop: while loops.
While loops consist of two parts: a condition, and a body. The body is the code that is execute inside the loop and the condition states under what conditions we should execute this code again and under what conditions we should continue past the loop.
Simple examples
Consider the following example:
counter = 0
while counter < 10:
print "hello world"
counter = counter + 1
In this example, the condition is "counter < 10": the loop should continue to execute the body code while the variable "counter" is less than 10. The body of the code is to print "hello world" and increment the counter. The result of this code will be to print "hello world" 10 times.
In the general case, a while loop looks like this:
while <condition>
<body>
You might notice that this looks rather like an [[ifstatements|if statement]]. In fact, a while loop is very like an if statement, except that in the case of an if statement, if the condition is true, the body executes only once and then moves on. If the condition in a while statement continues to be true, the body code will execute over and over again until the condition becomes false.
Even the simple code we've seen already can be used for some of the "real world" example we've discussed already.
cardsperhand = 5
cardsinhand = 0
while cardsinhand < cardsperhand:
dealOneRound()
cardsinhand = cardsinhand + 1
this code (given an implementation of "dealOneRound()") will deal a hand for poker.
For loops
The other main looping construct provided by Python is the for loop. A for loop also has a loop body, but instead of a condition uses a special variable called an iterator, set to different parts of a related data structure. Take this example:
mystr = "Peter"
for letter in mystr:
print letter
This code prints each individual letter from the string "Peter". Each time the body of the loop executes, the iterator "letter" is set to the next letter of the string.
Here's another example:
mylist = [1,6,2,6,7,3]
count = 0
for item in mylist:
count = count + item
This adds up the numbers in a list. Note that the iterator "item" is set to the next item in the list each time.
Showing while and for loops are equivalent.
To prove the two are equivalent, here is the same problem (counting the instances of a particular string in a list of strings) coded twice with the different constructs:
Using a for loop:
mylist = ["Peter", "Paul", "Mary", "Peter"]
count = 0
for name in mylist:
if name=="Peter":
count = count + 1
Using a while loop:
mylist = ["Peter", "Paul", "Mary", "Peter"]
count = 0
index = 0
# len(mylist) gives the length of mylist
while index < len(mylist):
# getting the name from the list using index
name = mylist[index]
if name=="Peter":
count = count + 1
index = index + 1
Why use for loops?
Just as we try to write while loops that look like English, we should do the same with for loops. In the example above, "for each name in the list" makes more sense than "while the index is less than the length of the list" and therefore the code is clearer. Code should be written to be easy to read, as well as to perform the task!
Where is the condition?
It may look like, unlike a while loop, a for loop does not contain a condition. In fact, it does. The condition is when the iterator runs out of things to be set to - when it reaches the end of the string or list.
Should I use a for loop or a while loop?
The rule of thumb to decide is this:
If you know on entering the loop how many times you want to execute the body of the loop use a for loop. Otherwise, use a while loop.
Note that looping over a string or list counts as "knowing how many times" because you know on entering the loop how long the string or list is.