Skip to main content

Section 8.2 The for loop revisited

Recall that the for loop processes each item in a list. Each item in turn is (re-)assigned to the loop variable, and the body of the loop is executed. We saw this example in an earlier chapter.
We have also 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.
To review, the variable theSum is called the accumulator. It is initialized to zero before we start the loop. The loop variable, aNumber will take on the values produced by the range(1, aBound + 1) function call. Note that this produces all the integers from 1 up to the value of aBound. If we had not added 1 to aBound, the range would have stopped one value short since range does not include the upper bound.
The assignment statement, theSum = theSum + aNumber, updates theSum each time through the loop. This accumulates the running total. Finally, we return the value of the accumulator.
Check Your Understanding

Checkpoint 8.2.1.

    The following code contains an nested loop. How many times will the phrase “We made it here!” be printed on the console?
    def printnums(x,y):
        for h in range(y):
            print("We made it here!")
            for i in range(x):
                print("We made it here!")
    
    printnums(5, 3)
    
  • 5
  • This is how many times the inner loop will print for each iteration of the outer loop.
  • 8
  • Keep in mind that the inner loop is part of the body of the outer loop.
  • 15
  • The inner loop will print a total of 15 times; however the outer loop is also printing the same phrase.
  • 18
  • Correct! The nested loop will be run 3 times, making a total of 18.
  • 20
  • Pay attention to the order of x and y
You have attempted of activities on this page.