8.2. The for loop revisited

We have seen iteration paired with the update idea to form the accumulator pattern. For example, to compute the sum of the first n integers, we could create a for loop using the range to produce the numbers 1 through n. Using the accumulator pattern, we can start with a running total variable initialized to 0 and on each iteration, add the current value of the loop variable. A function to compute this sum is shown below.

 
1
def sum_to(bound: int) -> int:
2
    the_sum: int
3
    i: int
4
    the_sum = 0
5
    for i in range(1, bound + 1, 1):
6
        the_sum = the_sum + i
7
    return the_sum
8
9
def main() -> None:
10
    print(str(sum_to(4)))
11
    print(str(sum_to(1000)))
12
    return None
13
14
main()
15

(ch07_summation)

To review, the variable the_sum is called the accumulator. It is initialized to zero before we start the loop. The loop variable, i will take on the values produced by the range(1, bound + 1, 1) function call. Note that this produces all the integers from 1 up to the value of bound. If we had not added 1 to bound, the range would have stopped one value short since range does not include the upper bound.

The assignment statement, the_sum = the_sum + i, updates the_sum each time through the loop. This accumulates the running total. Finally, we return the value of the accumulator.

You have attempted 1 of 2 activities on this page
Next Section - 8.3. The while Statement