Chapter 7

REPETITION

Topics Covered:

  • Repetition
  • While loop
  • For loop
  • Range()
  • Finding maximum

Repetition

Suppose a student was trying to compute the average of three exam scores. It would be relatively easy to construct a Python program to do this:

exam1 = float(input(“Enter exam #1 score: “))

exam2 = float(input(“Enter exam #2 score: “))

exam3 = float(input(“Enter exam #3 score: “))

average = (exam1 + exam2 + exam3) / 3.0

print(“The average is”, “%.1f”%average)

Okay, but what if there were five exam scores instead of three? Well, that’s obvious. Just create two more variables, add two inputs, and then divide the sum by 5.0 instead of 3.0:

exam1 = float(input(“Enter exam #1 score: “))

exam2 = float(input(“Enter exam #2 score: “))

exam3 = float(input(“Enter exam #3 score: “))

exam4 = float(input(“Enter exam #4 score: “))

exam5 = float(input(“Enter exam #5 score: “))

average = (exam1 + exam2 + exam3 + exam4 + exam5) / 5.0

print(“The average is”, “%.1f”%average)

Well, what if there were 100 exam scores? Of course, you could add another 95 variables and 95 input statements, but there must be an easier way. If we create a total variable and add each exam score to it once it’s been input, we don’t need to remember the exam scores. What we would like to do is repeat the same two instructions (input number, add it to the total) 100 times.

Perhaps the one feature of computers that has contributed the most to their success is their ability to repeat instructions until some type of event has taken place. There are several different instructions that can be used to implement repetitions within a Python program. These loop instructions, along with the selection instructions discussed in chapter 6, are examples of control structures, since they alter the sequential flow of the program.

The while Instruction

The first repetition instruction we’ll examine is the while instruction, which has the following form in Python:

while Condition:

   Action

As with the if statement, the component labeled Condition is any True or False expression, and is usually, but not always, some type of comparison. In operation, the instruction tells the computer to repeatedly:

a) Test the Condition to see if it is True

b) If the Condition is True, carry out the Action

The key feature that distinguishes this from an if statement is that fact that this sequence can be carried out over and over, as necessary, until the value of the Condition becomes False.

Like the if, the Action component of a while instruction may consist of more than just a single instruction. In this case, it is necessary to indent at the same level all of the instructions that make up the Action.

To illustrate the behavior of the while instruction, consider these examples:

sum = 0

number = 10

while number > 0:

   sum = sum + number

   number = number – 1

This instruction sequence will add the values 10, 9, 8, and so on, down to 1, to the variable sum. In other words, the instruction sequence is a long way to say:

            sum = 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1

In this example, the indenting of the block is needed to capture the two instructions that make up the Action. To see why this matters, take a look at the alternative:

sum = 0

number = 10

while number > 0:

   sum = sum + number

number = number – 1

In this case, even though both instructions were intended to be within the loop, the only instruction actually in the loop is sum = sum + number. Since the value of the variable number never changes from its initial setting of 10, this loop will never terminate. This type of (erroneous) program segment is called an infinite loop.

As a third example of the while instruction, consider this sequence:

sum = 0

number = 0

while number > 10:

   sum = sum + number

   number = number + 1

In this case, the apparent intent of the programmer was to count from 0 up to 10. However, because the Condition is incorrectly stated, the value of the Condition is initially False. When this occurs, Python will bypass the instructions that make up the loop entirely. The while instruction is commonly referred to as a pre-test loop structure; it tests the Condition at the very start of the loop, before it carries out the specified Action.

We have seen how useful the Python Interactive mode is for testing lines of code and experimenting. With multiple-line instructions like if statements or while loops, you can still use the Interactive mode. After typing the colon and ENTER after your control structure’s Condition, the cursor moves to the next line without displaying the >>> prompt. You can type as many instructions as you’d like into your block. Just hit ENTER twice after the final instruction in your block. Here is a simple while loop example tested in the Interactive window:

Before the loop, the variable num is initialized to 2. Since 2 is less than 20, the Condition is True and Action will be executed. In this case, the Action is two instructions, display num and its square, then increment num by 3. This process continues until num eventually reaches a value of 23, which is greater than 20, and causes the Condition to be False.

Let’s look at a full example of the while loop in action. The problem we want to solve: How long it will take to have half of a loan paid off? Before we jump into the code, let’s take a look at a flowchart that models a solution to this problem. Flowcharting a while loop looks very similar to that of an if statement. The Condition is represented by a diamond and arrows labeled True and False must exit this diamond.

In our solution, we will first ask the user to input the amount of the loan, the annual interest rate, and the monthly payment amount. We will initialize a balance variable to the loan amount and set a month variable to 1. Our Condition will check to see if the remaining balance is still greater than half of the original loan. For the Action of this while loop, the program will compute the interest, determine the new balance, and then output the month, interest, payment and balance. To compute the interest, the balance is multiplied by the annual interest rate. It is divided by 12 to convert it to a monthly rate and then divided by 100 to convert it from a percentage to a decimal number. The final step is to add 1 to the month before looping back to the Condition.

Flowchart Modeling a Loan Payoff.

Next, we will use the flowchart solution to show the Python program that solves this problem:

Below is the output of a sample run of the program. Suppose you bought a “new” car and took out a loan for $14,000. The annual interest rate was 6.25% and you decided you would make monthly payments of $500. You can see from the program run that you’ll be halfway to paying off that loan in just 16 months!

The for Loop

Another common and very powerful repetition structure in Python is the for loop. The for loop will iterate, or repeat, once for each item in a sequence. Each time through the loop, you can access the current item in the sequence using a variable. For example, if the sequence was 1, 2, 3, 4, 5, then the for loop variable will take on 1 the first iteration of the loop, 2 in the second iteration of the loop, and so on. The syntax of the Python for loop looks like this:

for Variable in Sequence:

   Action

The Sequence in this statement can take on many forms. We will see later that the Sequence may contain items in a list or even lines from a file. The most common use, though, is the range function. The reference range(m,n) – generates a Sequence m, m+1, m+2, …, n-1. Let’s take a look at a couple of examples from the Interactive mode:

In the first example, the range began at 3 and went up to 7, but not including 7. On each iteration of the loop, the current Sequence value was stored in the variable number, which was printed as the loop Action. In the second example, the variable item iterated from -3 to 2 and was also displayed during the loop’s Action.

Now would be a good time to see how we could use the for loop to solve a problem: Write a program that will display the world population through 2025. Assume that the population was 7 billion in 2011 and that it grows at a rate of 1.1% each year. The program should display the year and population for each year on a line together. Here is a look at one solution to this problem:

population = 7000000000

print(“Year     Population”)

for year in range(2011,2026):

    print(year, f”{round(population):15,d}”)

    population = 1.011*population

Shown below is the output when the program was executed. Notice that this program did not involve any keyboard input from the user.

There are a couple of things from the code above that probably need some explanation. First, since we wanted to iterate the year variable through 2025, the ending value in the range needed to be the next integer, 2026. To display the population, we first rounded it to the nearest integer. We then used an f-string to output using 15 total characters and commas between each 3-digit period.

Another way you could have written the formula for the population would be to say population = population + .011*population. In other words, the following year’s population will be the current population plus 1.1% times the current population.

If you were thinking that you could have solved this problem using a while loop instead of a for loop, you are absolutely correct. Shown next is the comparable Python program using a while loop. It produces the exact same output as the program with the for loop. You should notice, though, that the while loop version is actually two lines longer than the for loop version since it was necessary to initialize the variable year to 2011 before the loop and increment year during the Action of the loop.

population = 7000000000

year = 2011

print(“Year     Population”)

while year < 2026:

    print(year, f”{round(population):15,d}”)

    population = 1.011*population

    year = year + 1

In the previous for loop examples, the value of the control variable increased by one for each iteration. An alternate form of the range function can be used that allows a third parameter, usually referred to as the step. This will make much more sense after looking at a couple of examples using the Interactive mode:

In the first example, number began at 13 and stepped by increments of 2. When it reached 21, the loop terminated. In the second example, thing began at 0 and incremented by steps of 5 until reaching the ending range value 30. In the final example, item began at -5, incremented by steps of 3 and stopped when it reached 7.

INTERACTIVE – Loopy fun!

Before running the program below, try to predict its output.

Finding Maximum

A frequent problem to solve in computing involves finding a maximum (or minimum) value of a list of numbers. The algorithm to accomplish this is pretty straightforward:

  1. Set maximum to an artificially low value (smaller than any possible input)
  2. Loop once for each value
    1. Input a value
    1. If value is larger than maximum, then it becomes the new maximum

If you know in advance how many values you will have, a for loop is a good choice. Suppose we would like to ask the user how many values will be entered first. Then, the user will enter each value. You should note that these values could be exam scores, stock prices, fish weights, temperatures, etc. Our algorithm will work for any application. Here is a Python program that will implement a solution based on the algorithm above. The output for a sample run of the program is also provided.

A couple of observations from this program:

  • In the range, count+1 was used in order to loop count times.
  • To make a more sophisticated prompt for an input statement, you can precede a no-parameter input with a print statement that provides the prompt.
  • Because the program casts each input to a float, the user can enter integers or floating point numbers.

Chapter Review Exercises:

7.1. How many lines will get output when the following Python code is executed?

thing = 2

while thing < 10:

   print(thing)

   thing = thing + 1

7.2. How many lines will get output when the following Python code is executed?

thing = 2

while thing < 10:

   print(thing)

7.3. How many lines will get output when the following Python code is executed?

thing = 2

while thing > 10:

   print(thing)

   thing = thing + 1

7.4. How many lines will get output when the following Python code is executed?

for num in range(3,8):

   print(num)

7.5. How many lines will get output when the following Python code is executed?

for num in range(5,17,3):

   print(num)

Programming Projects:

7.1. Write a program that creates a table to display Fahrenheit-to-Celsius conversions. Use the following formula to do the conversions:

You should ask the user for start, end, and step values for Fahrenheit temperatures. The program should print column headings and the values printed should be displayed using 2 decimal places.

The sample interaction should look like this: