• Tidak ada hasil yang ditemukan

Chapter 2 Chapter 2

12.61 Definite Loops

2.6. Definite Loops 43

def main () :

print ("This program computes the average of two exam scores . ")

score!, score2 = eval (input ("Enter two scores separated by a comma: ") ) average = (score! + score2) I 2

print ("The average of the scores is: ", average) main ()

The program prompts for two scores separated by a comma. Suppose the user types 86, 92. The effect of the input statement is then the same as if we had done this assignment:

score!, score2 = 86, 92

We have gotten a value for each of the variables in one fell swoop. This example used just two values, but it could be generalized to any number of inputs.

Of course, we could have just gotten the input from the user with separate input statements:

score! - eval (input ("Enter the first score: ") ) score2 - eval (input ("Enter the second score: ") )

In some ways this may be better, as the separate prompts are more informative for the user. In this example the decision as to which approach to take is largely a matter of taste. Sometimes getting multiple values in a single input provides a more intuitive user interface, so it's a nice technique to have in your toolkit. Just remember that the multiple values trick will not work for string (non-evaled) input; when the user types a comma it will be just another character in the input string. The comma only becomes a separator when the string is subsequently evaluated.

go around (or iterate) the body of the loop. For example, the chaos program in Chapter 1 used a loop that always executed exactly ten times:

for i in range (10) :

X = 3 . 9 * X * (1 - X) print ( x)

This particular loop pattern is called a counted loop, and it is built using a Python for statement. Before considering this example in detail, let's take a look at what for loops are all about.

A Python for loop has this general form:

for <var> in <sequence>:

<body>

The body of the loop can be any sequence of Python statements. The extent of the body is indicated by its indentation under the loop heading (the for <var>

in <sequence> : part).

The variable after the keyword for is called the loop index. It takes on each successive value in the sequence, and the statements in the body are executed once for each value. Often the sequence portion consists of a list of values. Lists are a very important concept in Python, and you will learn more about them in upcoming chapters. For now, it's enough to know that you can create a simple list by placing a sequence of expressions in square brackets. Some interactive examples help to illustrate the point:

>>> for i in [0, 1, 2, 3]:

print (i) 0

1 2 3

>>> for odd in [1, 3, 5, 7, 9]:

print (odd * odd) 1

9 25

49 81

2.6. Definite Loops

Can you see what is happening in these two examples? The body of the loop is executed using each successive value in the list. The length of the list determines the number of times the loop executes. In the first example, the list contains the four values 0 through 3, and these successive values of i are simply printed. In the second example, odd takes on the values of the first five odd natural numbers, and the body of the loop prints the squares of these numbers.

Now, let's go back to the example that began this section (from chaos. py) Look again at the loop heading:

for i in range (10) :

Comparing this to the template for the for loop shows that the last portion, range (10) , must be some kind of sequence. It turns out that range is a built­

in Python function for generating a sequence of numbers "on the fly." You can think of a range as a sort of implicit description of a sequence of numbers. To get a handle on what range actually does, we can ask Python to turn a range into a plain old list using another built-in function, l ist:

>>> l ist (range (10) ) # turns range (10) into an expl icit l ist [0' 1' 2' 3' 4' 5' 6' 7' 8' 9]

Do you see what is happening here? The expression range (10) produces the sequence of numbers 0 through 9. The loop using range (10) is equivalent to one using a list of those numbers.

for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:

In general, range ( <expr>) will produce a sequence of numbers that starts with 0 and goes up to, but does not include, the value of <expr>. If you think about it, you will see that the value of the expression determines the number of items in the resulting sequence. In chaos . py we did not even care what values the loop index variable used (since i was not referred to anywhere in the loop body). We just needed a sequence length of 10 to make the body execute 10 times.

As I mentioned above, this pattern is called a counted loop, and it is a very common way to use definite loops. When you want to do something in your program a certain number of times, use a for loop with a suitable range. This is a recurring Python programming idiom that you need to memorize:

45

for <variable> in range (<expr>) :

The value of the expression determines how many times the loop executes. The name of the index variable doesn't really matter much; programmers often use i or

j

as the loop index variable for counted loops. Just be sure to use an identifier that you are not using for any other purpose. Otherwise you might accidentally wipe out a value that you will need later.

The interesting and useful thing about loops is the way that they alter the

"flow of control" in a program. Usually we think of computers as executing a series of instructions in strict sequence. Introducing a loop causes Python to go back and do some statements over and over again. Statements like the for loop are called control structures because they control the execution of other parts of the program.

Some programmers find it helpful to think of control structures in terms of pictures called flowcharts. A flowchart is a diagram that uses boxes to represent different parts of a program and arrows between the boxes to show the sequence of events when the program is running. Figure 2.3 depicts the semantics of the

for loop as a flowchart.

<va r> = next item

<body>

Figure 2.3: Flowchart of a for loop

2.7. Example Program: Future Value

If you are having trouble understanding the for loop, you might find it useful to study the flowchart. The diamond-shaped box in the flowchart represents a decision in the program. When Python gets to the loop heading, it checks to see if there are any items left in the sequence. If the answer is ''yes," the loop index variable is assigned the next item in the sequence, and then the loop body is executed. Once the body is complete, the program goes back to the loop heading and checks for another value in the sequence. The loop quits when there are no more items, and the program moves on to the statements that come after the loop.