The Accumulator Pattern
When writing for
loops there are certain patterns that you will see over and over and over again. The accumulator pattern is the most common.
Say, for example, that we want to count the number of times that a for
loop runs.
Here, we get a name error. This is equivalent to saying something like x = x + 1
when we haven’t yet declared x as a variable.
The accumulator pattern looks like:
Think of the accumulator pattern as what allows your program to remember values across iterations of a for loop.
# TODO: Modify the following code to accumulate the sum of all values
# that the loop loops over (in this instance, sum the numbers 1 through 12)
secret_number = 12
count = 0 # 1) declare your accumulator variable
for num in range(secret_number):
count = count + 1 # 2) update your accumulator variable
print(count) #
This is the pattern that you will use to create new strings with for loops, calculate factorials (n!), calculate numbers in the fibonacci sequence, and generally update values as iterations happen.
Some non-working examples
Let’s examine why the following example doesn’t work (even though they don’t cause errors).