|Chapter 7: Input||Chapter 9: A Simple Example|
Say we wanted to write a program that asked the user how many times they wanted a phrase repeated. (Yes, it really is necessary to have these silly examples. More realistic examples are often too complex to demonstate a single new concept.)
print "How many times?" count = input() if count == 1: print "Are we there yet?" if count == 2: print "Are we there yet?" print "Are we there yet?" if count == 3: print "Are we there yet?" print "Are we there yet?" print "Are we there yet?" if count == 4: print "Are we there yet?" print "Are we there yet?" print "Are we there yet?" print "Are we there yet?"
If you run this program, the user will be asked “How many times?” and the computer will wait for an answer. The user can then type a number between 1 and 4 and the phrase “Are we there yet?” will be displayed that many times. There are several problems with this program. Firstly, it can at most handle a count of 4. If the user wants it displayed 5 times, the program must be extended to handle that case. Secondly, as the number of cases grows, it will be difficult to make sure that the program is correct. If you extend it all the way to, say, 20 times, it’s difficult to check using your text editor that the case for 17 really has 17 lines in it. Perhaps you made an error and only cut-and-pasted the line 16 times. We could be clever and rewrite it like this:
print "How many times?" count = input() if count >= 1: print "Are we there yet?" if count >= 2: print "Are we there yet?" if count >= 3: print "Are we there yet?" if count >= 4: print "Are we there yet?"
This is somewhat tricky, so it’s important to follow the logic
carefully, as the computer would. Let’s say count is 3.
The first “if” statement will check if 3 is greater than or
equal to 1, and since it is, print the first phrase. The
next “if” will compare count to 2, and print the second phrase.
The same thing will happen when
count >= 3 is tested,
since 3 is greater than or equal to 3. But the fourth test
will not work, since 3 is not greater than or equal to 4.
So the fourth phrase will not be displayed. The phrase will
have been displayed 3 times (once for each of the first three
“if” statements), which is what we wanted since count is 3.
This new way of writing the program is simpler to verify for correctness. We just need to make sure that each number in successive “if” statements is one more than the previous number. Since each “if” statement only prints a single line, we don’t risk mis-counting the number of “print” lines as in the first example. But it’s still somewhat tedious to extend the program to handle higher values of count. You have to cut-and-paste two lines and remember to increase the number in the “if” statement.
We could make that a little easier with this new version:
print "How many times?" count = input() if count >= 1: print "Are we there yet?" count = count - 1 if count >= 1: print "Are we there yet?" count = count - 1 if count >= 1: print "Are we there yet?" count = count - 1 if count >= 1: print "Are we there yet?" count = count - 1
Now the program is more complicated, but each “if” statement is identical. That makes cutting and pasting much easier—we can simply hold down the Ctrl-V key (Paste) and have a program that handles very large values of count. Here’s how the new program works. The first “if” statement, as before, compares count to 1 and prints the phrase if count is greater than or equal to 1. But it also does something else: it decreases the value of count by one. This statement:
count = count - 1
does three things: it finds the value of count in memory, subtracts 1 from it, and puts the result back into memory, replacing the old value of count. So if count is 3, the count on the right side is replaced with its value:
count = 3 - 1
then the arithmetic is done:
count = 2
and the new value is stored into memory as before, replacing the 3 that was there. You may wonder why only the count on the right side of the equal sign gets replaced with its value, and not the left. Why doesn’t the computer replace both words with the value 3, like this:
3 = 3 - 1
Obviously this wouldn’t be very useful. The assignment statement only looks up the existing value of variables when they appear on the right of the equal (assignment) sign. The single variable on the left of the equal sign is used as-is to know what name to associate with the result of the arithmetic on the right.
So after the first phrase is displayed, count is decreased
by one, and the next “if” is tested. It’s the same test, comparing
count with 1. Say that count is 3 initially. At
the first “if” we’ll see the phrase displayed and count will become
2. At the second “if” we’ll see the phrase and count will become
1. At the third “if” we’ll see the phrase and count will become
0. At the fourth “if” the test “0 >= 1” will not be true, so the
phrase won’t get displayed and count won’t be decreased. No
matter how many more “if” statements you have after that, the
value of count will stay 0 and none of the
Our program now has one final problem: no matter how many times we cut-and-paste these three lines, the user could always enter a number that’s higher than that. You could have pasted the “if” statement 500 times, and if the user enters “510”, your program will only display the phrase 500 times, once for each “if”. The program will end with the variable “count” set to 10, since there are 10 more phrases to go, but the last 10 “if” statements won’t be there.
We can fix this last problem with a loop, like this:
print "How many times?" count = input() while count >= 1: print "Are we there yet?" count = count - 1
That’s the entire program. Specifically, this is a while loop (there are several different kinds). We removed all the “if” statements except one, and replaced the word if with the word while. It almost reads like an English sentence: “While count is greater than or equal to 1, print this phrase and decrease count by one.” Let’s “play computer” with count initially set to 3. The computer will get to the “while” statement, compare 3 to 1, see that 3 is greater than or equal to 1, display the phrase, decrease count by 1 (to 2), and loop back up to the while statement. Again the computer will compare count to 1, and since 2 is greater than or equal to 1, it will print the statement, decrease count to 1, loop back up, compare count with 1, and since 1 is greater than or equal to 1, display the phrase and decrease the variable count to zero. It will then loop back up to the “while” statement, compare count to 1, and since 0 is not greater than or equal to 1, the indented statement will not be run and the “while” loop will finish, moving on to the statements that follow. In this program there are no statements that follow, so the program will end. Each time through the loop is called an iteration.
There are several different types of loops. Which one to use depends both on what’s available in the programming language you’re using and which makes the most sense for what you’re trying to do. For example, in the example above, we could print the value of count in each iteration, like this:
print "How many times?" count = input() while count >= 1: print "Are we there yet?" print count count = count - 1
Running the program would look something like this (if the user typed “3” when asked):
How many times? 3 (what the user types in) Are we there yet? 3 Are we there yet? 2 Are we there yet? 1
The numbers 3, 2, 1 are the values of count at each iteration. What if, instead, just wanted to count upwards? Or what if you didn’t want to modify count, because you wanted to use it later on in the program? You could use a for loop, like this:
print "How many times?" count = input() for i = 1 to count: print "Are we there yet?" print i
(Note: So far the language we’ve used for examples has been similar to the popular programming language Python. But Python has no such for loop. The above syntax is based on the language Basic.)
This for loop means, “Run the indented statements once for each value between 1 and count, and set the variable i to that value.” If the user enters 3 you’ll see this:
How many times? 3 Are we there yet? 1 Are we there yet? 2 Are we there yet? 3
The 1, 2, 3 are the values of i at each iteration. Note that we no longer need to decrease the value of count in each iteration. The computer automatically increases i by 1 each iteration until it reaches count. In fact, count is unchanged after the loop finishes. This loop:
for i = 1 to count: print i
is essentially identical to this version:
i = 1 while i <= count: print i i = i + 1
The for loop is generally preferable to while loops when you want to cover a range of numbers. It’s shorter and easier to read. The while loop, though, is more flexible since you’re doing all the work yourself. You could increment i by 2 at each iteration to see only the odd numbers, or you could double the value of i to see all the powers of two:
print "What is the maximum?" maximum = input() i = 1 while i <= maximum: print i i = i * 2
What is the maximum? 128 1 2 4 8 16 32 64 128
You can’t do that with a simple for loop. Incidentally, in a for loop the starting and ending values (1 and count in our example) can actually be any pair of numbers. You could do:
for i = 20 to 24: print i
to display the values 20, 21, 22, 23, and 24. The variable i is used here, but any variable could be used. i is a commonly-used variable for for loops; it stands for index. You could also use a variable name that makes more sense in your particular context, such as:
for year = 1992 to 2004: print "The year is " + year
Another type of loop is the foreach loop. That’s similar to the for loop except that the variable doesn’t just go through a numerical range, it’s actually set to each element in a set of numbers:
foreach year in [1992, 1996, 2000, 2004]: print "The " + year + " Olympic Games."
That also reads almost like an English sentence: “For each year in the list 1992, 1996, 2000, 2004, print this statement.” (Note: Python does have such a for loop, except the word for is used instead of foreach.)
There are a few other types of loops, but they’re usually variations on the above three types.
|Chapter 7: Input||Chapter 9: A Simple Example|