For our second example, suppose we have a list of the ages of every person in Utah and we want to calculate the average age.
Looking at census data for 2020, the population of Utah was 3,271,616 people. It would be absurd to try to manually calculate the average of that many numbers (ages). So, if we have a list of all the ages (let's say in a file), we could read those numbers into a Python program, add them all up and then divide by 3,271,616. To do this efficiently, we would use a repetition structure.
Here's a description and flowchart of how we might approach this problem:
As depicted in the flowchart, a common approach would be to set a variable that will hold our running total age (we call this an accumulator). Then we read each age from the data source (we'll learn more about how to read data from outside sources later) and in a repetition structure (loop) we add each newly read age to the accumulator. We repeat that step over and over until there are no more pages to read from the data source. In this example, the loop would repeat 3,271,616 times. When it exits the loop, the accumulator would contain the total age. We could then calculate the average age after the loop by dividing the total age by the number of ages.
In the following several pages we will take a look at the while loop and the for loop which are two of the primary repetition structures that we use in programming. We'll also look at several examples of problems that are solved by repetition structures.