Loop Patterns

For and while loops are often used to go through list of items or the contents of a file to look for largest or smallest value of data. These loops are generally constructed by:
  • Initializing one or more variables before the loop starts.
  • Performing some computation on each item in the loop body, possibly changing the variables in the body of the loop.
  • Looking at the resulting variables when the loop completes.


To count the number of items in a list, we would write the following for loop:
count = 0
for itevar in [2,3,41,32,53,3]:
    count = count + 1
print 'Count: ', count
In order to count the members of a list we set the count variable to 0 before the for loop starts, then we write the for loop to run through the list of numbers. The iteration variable is named ‘itevar’ and while we don’t use itevar in the loop, it does control the loop and cause the loop to be executed once for each of the values in the list.
In the body of the loop, we add one to the current value of count for each of the values in the list. So while the loop is executing, the value of count is the number of values we have seen ‘so far’. Once the iterations in the for loop are completed, the value of count is the total number of items. The total number of counts is printed out at the end of the loop.
total = 0
numbers =list(xrange(0,1000,2))
for number in numbers:
    total = total + number
print 'Total: ', total
Total: 249500
In this example we’ve used Python built-in function xrange and list function. List() function is used to create an empty list and xrange(0,1000,2) is function which gives us numbers from 0 to 1000 with step of 2 which means even numbers. Total is variable which is set to zero before the for loop starts and then for each iteration the total is updated with a number from a numbers list. After the for loop is completed the program will print out the total sum of numbers in the list called numbers which is 249500.
So as the loop executes, the total accumulates the sum of the elements; a variable used this way is sometimes called an accumulator.


To find the largest value in a list or sequence, we construct the following loop:
largest = None 
print 'Before: ', largest
numbers = [3, 45, 28, 128, 74, 154, 21]
for number in numbers:
    if largest is None or number > largest:
        largest = number 
    print 'Loop:', number, largest
print 'Largest:', largest
When the program executes the output is as follows:
Before:  None
Loop: 3 3
Loop: 45 45
Loop: 28 45
Loop: 128 128
Loop: 74 128
Loop: 154 154
Loop: 21 154
Largest: 154
The largest variable is best thought as the ‘Largest value we have seen so far’. Before the loop, the initial value of the largest variable is set to None. None is special constant value which we can store in a variable to mark the variable as “empty”.
Before the loop starts we’ve printed out the value of the largest variable which is None using Python built-in function called print. We’ve also defined list called numbers which has 7 elements (numbers). While the loop is executing, if largest is None then we take the first value we see as the largest so far. As you can see in the first iteration when the value of number is 3, since initial value is None, we immediately set largest to be 3.
After the first iteration, largest is no longer None, so the second part of the compound logical expression that checks number>largest triggers only when we see a value that is larger than the largest so far.
At the end of the loop, we’ve scanned all of the values and the variable largest now does contain the largest value in the list.
To compute the smallest number, the code is very similar with one small change:
smallest = None
print "Before: ", smallest
numbers = [3, 45, 28, 128, 74, 154, 21]
for number in numbers:
    if smallest is None or number < smallest:
        smallest = number 
    print 'Loop:', number, smallest
print 'Smallest: ', smallest
Again, smallest is the “smallest so far” before, during, and after the loop executes. When the loop has completed, smallest contains the minimum value in the list. Again as in counting and summing, the built-in functions max() and min() make writing these exact loops unnecessary.

Before:  None
Loop: 3 3
Loop: 45 3
Loop: 28 3
Loop: 128 3
Loop: 74 3
Loop: 154 3
Loop: 21 3
Smallest:  3

Nema komentara:

Objavi komentar