There’s a Pattern Here!¶
There’s a pattern in these programs, a pattern that is common when processing data. We call this the Accumulator Pattern. In the first program above, we accumulated the values into the variable
sum. In the last few programs, we accumulated a product into the variable
Here are the five steps in this pattern.
Set the accumulator variable to its initial value. This is the value we want if there is no data to be processed.
Get all the data to be processed.
Step through all the data using a
forloop so that the variable takes on each value in the data.
Combine each piece of the data into the accumulator.
Do something with the result.
Using the Accumulator Pattern¶
What is the sum of all the numbers between 1 and 100? We can answer that easily using our pattern.
range function has one more version that we can use here. By providing three input numbers, we can specify the start value, the ending value (which is one more than the last value), and the step – how much to change between numbers.
Now let’s answer a slightly harder question: What is the sum of all the even numbers between 0 and 100? It’s easy with our pattern.
How do we know what’s really going on in this program? How do we know that number is taking on all of the even values from 0 to 100? One way we can tell is by using a CodeLens on a smaller problem from 0 to 20. We can step through the program line-by-line, or race to the end by clicking the Last button and then step backwards.
Discuss topics in this section with classmates.