Skip to main content

Section 5.6 Loop patterns

Often we use a for or while loop to look for something such as the largest or smallest value of the data in a list of items or the contents of a file.
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
We will use a list of numbers to demonstrate the concepts and construction of these loop patterns.

Subsection 5.6.1 Counting and summing loops

For example, to count the number of items in a list, we would write the following for loop:
We set the variable count to zero before the loop starts; then we write a for loop to run through the list of numbers. Our iteration variable is named itervar, and while we do not use itervar in the loop, it does control the loop and cause the loop body to be executed once for each of the values in the list.

Checkpoint 5.6.1.

    Q-2: Which variable is the iteration variable in the following code block?
    count = 0
    for item in [3, 41, 12, 9, 74, 15]:
        count = count + 1
    print('Count: ', count)
    
  • item
  • Correct! item is the iteration variable.
  • count
  • Incorrect! count is a variable counting the iterations. Try again.
  • [3, 41, 12, 9, 74, 15]
  • Incorrect! This is a list. The program counts the number of values in the list, but the list is not the iteration variable. Try again.
  • list
  • Incorrect! This loop iterates through a list, but there is no variable named list. Try again.
In the body of the loop, we add 1 to the current value of count for each of the values in the list. While the loop is executing, the value of count is the number of values we have seen “so far”.
Once the loop completes, the value of count is the total number of items. The total number “falls in our lap” at the end of the loop.
Another similar loop that computes the total of a set of numbers is as follows:
In this loop we do use the iteration variable, and we have called it number. Instead of simply adding one to the count as in the previous loop, we add the actual number (3, 41, 12, etc.) to the running total during each loop iteration. If you think about the variable total, it contains the “running total” of the values so far. So before the loop starts, total is zero because we have not yet seen any values. During the loop, total is the running total, and at the end of the loop total is the overall total of all the values in the list.
As the loop executes, total accumulates the sum of the elements. A variable used this way is sometimes called an accumulator.

Checkpoint 5.6.2.

Q-4: The variable that counts the sum of elements in a loop is called a(n) ________
Neither the counting loop nor the summing loop are particularly useful in practice because there are built-in functions len() and sum() that compute the number of items in a list and the total of the items in the list respectively.
However, in statistics, we often need to find the sum of the squares of a list of numbers. For example, the sum of squares of the numbers 3, 7, 5, and 4 is \(3^2 + 7^2 + 5^2 + 4^2\text{,}\) and there is no readily built-in function to handle that.

Checkpoint 5.6.3.

Write a program that will calculate the sum of squares of the list [3, 7, 5, 4]. Instead of total, you might want to name your accumulator sum_of_squares.
Solution.
sum_of_squares = 0
for number in [3, 7, 5, 4]:
    sum_of_squares = sum_of_squares + number **2
print("The sum of squares is", sum_of_squares)

Subsection 5.6.2 Maximum and Minimum Loops

To find the largest value in a list or sequence, we construct the following loop:
When the program executes, the output is as follows:
Before: None
itervar is 3 largest is 3
itervar is 41 largest is 41
itervar is 12 largest is 41
itervar is 9 largest is 41
itervar is 74 largest is 74
itervar is 15 largest is 74
Largest: 74
The variable largest is best thought of as “the largest value we have seen so far.” Before the loop, we set largest to the constant None. None is a special constant value which we can store in a variable to mark the variable as “empty”.

Checkpoint 5.6.4.

    Q-6: Which of the following is not true about None?
  • It is a constant value.
  • Incorrect! None is a constant value. Try again.
  • It is a variable.
  • Correct! None is a constant value that can be assigned to a variable, not a variable itself.
  • It marks a variable as empty.
  • Incorrect! None marks a variable as empty. Try again.
  • The value of a variable that starts off as None can change.
  • Incorrect! The value of None only means that the variable is empty. The variable can then be updated or reassigned. Try again.
Before the loop starts, the largest value we have seen so far is None since we have not yet seen any values. While the loop is executing, if largest is None then we take the first value we see as the largest so far. You can see in the first iteration when the value of itervar is 3, since largest 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 itervar > largest triggers only when we see a value that is larger than the “largest so far”. When we see a new “even larger” value we take that new value for largest. You can see in the program output that largest progresses from 3 to 41 to 74.
At the end of the loop, we have 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:
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. However, we have put them here because they are good examples of using a for loop.

Checkpoint 5.6.5.

Here is a mash-up of the counting and minimum programs. Write a program that asks the user for a number and then counts how many entries in the list [10, 66, 47, 11, 5, 2, 17, 54, 40] are less than the user’s number. For example, if the user enters 29, the program would report that there are 5 numbers less than 29. Note: you will not need to use None in this program.
Solution.
user_number = int(input('Enter your number: '))
n_smaller = 0
for number in [10, 66, 47, 11, 5, 2, 17, 54, 40]:
    if number < user_number:
        n_smaller = n_smaller + 1

# make grammatically correct output
if n_smaller == 1:
    print(n_smaller, 'item is less than', user_number)
else:
    print(n_smaller, 'items are less than', user_number)