While-loops can also be used to execute a block of code a predetermined number of times. These are called counting loops because an integer variable is used to count the number of times the block has executed, and the loop condition is such that the condition is True if the loop has executed fewer than the required number of times. The following example uses a while-loop to draw 10 progressively smaller circles inside one another:
In this example, we use two variables that are repeatedly updated in the body of the loop. The size variable keeps track of the size of the circle diameter we are drawing. The first time the loop is executed we draw a circle of diameter 100, but the diameter of each circle will get smaller and smaller with each iteration. The count variable is simply used to keep track of how many circles have been drawn; so long as count is less than 10, we will keep drawing more circles. Every time we draw a circle, we increase count by one, thus the count = count + 1 statement on the last line of the loop’s body.
Don’t forget to update counter variables within loops; it is a common error that often leads to infinite loops (we will come back to those shortly).