< Back

Activity 9

Accumulator

The accumulator pattern is a very common and useful technique in programming. Because we use this pattern frequently it is worth practicing on some simple examples to make sure that you understand it completely.

Reusing Variables

  1. Fill in the following table. For each row of the table, write what the following function prints to the terminal window. Put the result in the column on the right.

    ExecuteResult
    x = 7
    x = x + 5
    print(x)
    x = 7
    x += 7
    print(x)
    x = 7
    x -= 7
    x *= 2
    print(x)
    x = 5
    y = 7
    x = x + y
    print(x)
    x = 5
    y = 7
    x += y
    print(x)

Accumulator Pattern

  1. Consider the following Python programs. Write what you think each program will print to the terminal without typing in and running the code.

    ProgramOutput
    x = 0
    for i in range(10):
        x = x * i
    
    print(x)
    
    x = 1
    for i in range(5):
        x *= i
    
    print(x)
    
    x = 5
    for i in range(5):
        x -= i
    
    print(x)
    
    x = 1
    y = 2
    for i in range(5):
        x += i
        y += x
    
    print(y)
    
    x = 0
    y = 1
    z = 2
    for i in range(5):
        x = i
        y = i
        z = x + y
    
    print(z)