As this chapter begins you should be feeling pretty good about yourself. Let's go over it again to make sure you know what is going on. You can now: print things, do math, get input from the user, save data for later use, use someone else's code, use a hazy sense of intuition to sanity check that you are not about to try finding the sum of 12 and "frazz", and do different things based on the data you have in hand. All in all, you can do a lot. But currently if you wanted to, say, print out your name 12 times, you waould have to use the code:
and that sure is a lot of typing. Programmers hate typing. The more code you have to write to solve a problem, the more chances bugs have to slip in, and the more code you'll have to change if you want it to do something different. Loops are a method of saying "execute the following code this many times", or even saying "as long as this condition remains true, keep executing this code". Those two types of loops are called for loop
s and while loop
If you want to do something to every piece of data in an array, then for loops are exactly what you want to use. Let's say that you wanted to print out, in order, every element of the array
[ 'what', 'is', 'going', 'on?' ] with every word on a separate line. Well, assuming this data is in an array called
words you could do the following:
for i in words:
More generally, this construct
is formatted as:
for NAME in ARRAY:
, which is all just Python's way of constructing the following english sentence:
For every element of the array, starting at the beginning of
ARRAY, take each element in turn and put it in variable
NAME and execute
This, combined with the
which takes in a number and returns an array of integers from 0 up to one less then that number, means that you can now execute a given command a certain number of times!1
This is quite useful, because it means we can change our name-printing code into the much more succint:
for i in range(12):
This, as conform
pointed out, not only saves you from a lot of typing, and a lot of editing if you want to change the string, but also clearly shows the number of times thestring will get printed out. It's a form of documentation as well as code! It's a win-win situation involving synergy and leveraging trajectories to enhance our quality vector!
Not only that, but a very common idiom
is to combine the
functions to create code that modifies every element of the array.2
Not only that, but just like you can nest if/then statements, you can also nest loops together. Or you can put loops in ifs, or, more generally, you can put any indented block structure inside any other indented block structure. This might be used like the following:
words = [ "foo", "Food", "dOOOf" ]
for i in range(len(words)):
for j in range(len(words[i])):
if words[i][j] == "d":
words[i][j] = "D"
(Exercise - run this code. What does it do? Is that a useful thing for it to do? How could this technique be useful?)
for loops are for iterating over a set of values. But what if you want to keep iterating as long as something is true? That's when you need:
The other method of looping is the
while loop. It gets used for situations when you are not quite sure how many times you will need to go through a loop, you just know that you need to do it until some condition is met. One possibility is the game from previous chapters, but made better:
number = 7
guess = int(raw_input("What number am I thinking of?"))
while guess != number:
if guess < number:
print "Nope, too low"
print "Nope, too high"
guess = int(raw_input("What number am I thinking of?"))
print "You got it!"
Like in the previous section, this game isn't very fun, but it is a lot more fun than its previous incarnation. Looking at this loop and attempting to decipher would hoepfully lead you to conclude that the general form of
which corresponds to the english sentence "As long as CONDITION is true, execute INSTRUCTIONS again". Note that this makes it pretty easy to create an infinite loop
. This would be a bad thing, because your program would never end, so make sure that your code makes sense, and that your condition will eventually become false. If, in your own code, you happen to create something that has an infinite loop, type Control-C
to stop the program.
while loops are especially useful for times like in the example above. We don't know when the user will guess the number correctly, so we don't know how many loops to go through with the
for loop. On the other hand, we are giving hints about what the correct answer is, so anybody who knows what order the numbers go in should be able to guess it eventually.
Now comes the obligatory imperative to play around with these. Just muck around. Alter the game above to make it a random number - notice how the game is a lot more fun? Think about what problems you are trying to solve. It is quite possible that you now know enough to complete those projects! If so, then congratulations! Go do that. Of course, if, as you are writing your code, you discover it turning into a twisty maze of confusing statements with lots of code repeated, go to the next chapter to get what you need!
You can, of course nest these loops as well, but before you start nesting construct within construct leading to so many spaces to the left of your code that you don't even know what is going on, you should check out the most popular method of fixing that issue - by making your own functions.
<< | Learn to Program | >>
- m_turner pointed out, quite rightly, that this type of for loop is relatively unique to python. In other languages you will encounter ones that are a lot more like the ones in the for loop node. Go there to do more research on the subject, but you should realize that this idiom is relatively Python specific.
for() loops, i is almost always the loop iteration variable, and if loops are nested the next one is j, and the next one is k. This is especially true if these numbers are integers, which is often the case. This is a cultural thing, and is a historical oddity that continues mostly due to the fact that everyone does it that way.