Python: Introduction

Iteration

Iteration

Learning Outcomes

On completion of this section you will know how to use:

Introduction

Iteration means doing something repeatedly, i.e. again and again. In programming it means repeating a group of programming lines a number of times. This is a major departure from the programs we have written so far.

The sequence of our programming has up to now gone from top to bottom. In the simple programs that we have looked at execution started at the first line and continued downwards to the last line. No line was skipped and no line was executed more than once. Also no line was executed until the previous line completed its task.

In Exercise 4 of the page Expressions you were required to write a program that accepted the details of three transactions from a user. The required program would look somewhat like Listing 1 below.

Listing 1
                         #Exercise 4
                         #First sale
                         strNameOfCustomer = input("Enter name of customer: ")
                         intItemsSold = int(input("Enter amount sold: "))
                         floatCostOfItem = float(input("Enter cost of one item: "))
                         floatCostOfSale = intItemsSold * floatCostOfItem
                         print("Name of customer: ", strNameOfCustomer)
                         print("Amount sold: ", intItemsSold)
                         print("Cost of one item: ", floatCostOfItem)
                         print("Cost of sale: ", floatCostOfSale)
                         #Second sale
                         strNameOfCustomer = input("Enter name of customer: ")
                         intItemsSold = int(input("Enter amount sold: "))
                         floatCostOfItem = float(input("Enter cost of one item: "))
                         floatCostOfSale = intItemsSold * floatCostOfItem
                         print("Name of customer: ", strNameOfCustomer)
                         print("Amount sold: ", intItemsSold)
                         print("Cost of one item: ", floatCostOfItem)
                         print("Cost of sale: ", floatCostOfSale)
                         #Third sale
                         strNameOfCustomer = input("Enter name of customer: ")
                         intItemsSold = int(input("Enter amount sold: "))
                         floatCostOfItem = float(input("Enter cost of one item: "))
                         floatCostOfSale = intItemsSold * floatCostOfItem
                         print("Name of customer: ", strNameOfCustomer)
                         print("Amount sold: ", intItemsSold)
                         print("Cost of one item: ", floatCostOfItem)
                         print("Cost of sale: ", floatCostOfSale)
                    
Listing 1

This is a huge program, and we are only dealing with a very small number of customers. Imagine to size of a program that would deal with all of the customers that came into a busy store during the course of one day!

Again imagine if we had to keep track of all of the customers that came into the store in a single week! What about a whole year!

There are many problems associated collecting data this way. Two of the major problems are:

Are there any solutions to those problems? Yes there are. Its called Iteration. It is also called loops.

There are two types of loops: for loops and while loops. The former is the simplest and therefore we will start with that.

Go to top

The for loop construct

First example

Listing 2
                    
                        #For loop example 1
                        for intCounter in range(3):
                            strNameOfCustomer = input("Enter name of customer: ")
                            intItemsSold = int(input("Enter amount sold: "))
                            floatCostOfItem = float(input("Enter cost of one item: "))
                            floatCostOfSale = intItemsSold * floatCostOfItem
                            print("Name of customer: ", strNameOfCustomer)
                            print("Amount sold: ", intItemsSold)
                            print("Cost of one item: ", floatCostOfItem)
                            print("Cost of sale: ", floatCostOfSale)
                    
                    

Listing 2 above performs exactly the same function as Listing 1, i.e. it accepts values for three sales and prints out the details of each single sale including the calculated values. But it is only 10 lines, so how does it do it?

Look at line 2 for intCounter in range(3):. What does it mean?

Firstly the keyword for tells us that it is the start of a for loop. The next item intCounter is an integer variable that is used to keep track of how many times the loop has iterated. This variable is generally referred to as the 'loop counter' and normally the word 'counter' is part of its name, as in our example here. The penultimate part range(3) controls how many times the loop will iterate. The loop counter, intCounter in our case starts off at zero, then once the body of the loop has been executed once, its value is incremented by 1. The body of the loop is then executed one more time. This continues until the loop counter has a value equal to the value between the brackets of range(). Once this occurs the loop terminates.

Applying this to our example intCounter starts with a value of zero, then lines 3 - 16 are executed. Then intCounter is incremented to 1 and lines 3 - 10 are executed once more. Next intCounter is incremented to 2 and lines 3 - 10 are executed. After this intCounter is incremented to 3. This is the value between the brackets of range(), and therefor it provides the signal for the loop to stop iterating.

From the above we can summarise that in a simple loop like Listing 2 the loop counter starts off with a value of zero, then after each execution of the body of the loop the counter is incremented by 1. This continues until the loop counter has a value equal to that between the brackets of range(), after which the loop will stop iterating. Thus in Listing 2 the loop will iterate when intCounter has values of 0, 1 and 2 but stops when it reaches the value of 3.


Another example

Listing 3
                        #For loop example 1
                        print("This program will collect data about customer sales")
                        print("The data collected will be name of customer, amount sold and")
                        print("the cost of one item. ")
                        print("It will then calculate sales value.")
                        print("Finally it will print customer name, amount sold, cost of one item")
                        print("and total sale value")
                        print("*********************************************")
                        for intCounter in range(3):
                            strNameOfCustomer = input("Enter name of customer: ")
                            intItemsSold = int(input("Enter amount sold: "))
                            floatCostOfItem = float(input("Enter cost of one item: "))
                            floatCostOfSale = intItemsSold * floatCostOfItem
                            print("Name of customer: ", strNameOfCustomer)
                            print("Amount sold: ", intItemsSold)
                            print("Cost of one item: ", floatCostOfItem)
                            print("Cost of sale: ", floatCostOfSale)
                        print("*********************************************")
                        print("The program has now completed its processing")
                        print("If further processing is required the program must be run again")
                    

Notice that lines 9 - 17 in listing 3 are identical to lines 2 - 10 in Listing 2. This means that the processing of the two programs is identical. From a pedagogical point of view however Listing 1 may give the impression that a for loop actually takes over the entire program and that every line of the program will be executed. This is not the case as shown by Listing 3. Here the loop is shown as being part of a larger program. Lines 2 - 8 and 19 - 20 are not part of the loop and will, therefore execute only once. Line 9 is the loop controller and lines 10 - 17 form the body of the loop. From line 9 we can deduce that the loop will iterate three times - with the loop counter having values of 0, 1 and 2 - and thus lines 9 - 17 will be the only lines that will be repeated.

Let us now look at the features of the loop as part of a larger program:


What about sequence?

Before beginning on Iteration you would have been familiar with the concept of sequence, i.e. that program execution starts at the first line and continues downwards line by line until the final line is executed. Does iteration contradict this top to bottom sequence? No it does not; it simply adds some flexibility to the concept.

Examining Listing 3, we see that lines 2 - 8 will be executed in order. Control then passes to line 9 - the start of the loop. This loop extends down to line 17 and thus lines 9 - 17 will be executed three times. During each of those executions lines 9 - 17 will be executed in the strict order of their sequence. Once lines 9 - 17 has been executed three times lines 19 and 20 will be executed thus finishing the program.

Go to top

The while loop construct

We don't know how many times the loop will iterate

In Listing 2 and Listing 3 above we used a very unrealistic example; customers may want to purchase more than one item and different items will have different prices. As we don't know how many items each customer may buy we shall look at a program which, instead of iterating exactly three times will iterate for exactly as many times as the user requires.

Listing 4
                    
                        #While loop example 1
                        strNameOfCustomer = input("Enter name of customer: ")
                        while strNameOfCustomer != "":
                            intItemsSold = int(input("Enter amount sold: "))
                            floatCostOfItem = float(input("Enter cost of one item: "))
                            floatCostOfSale = intItemsSold * floatCostOfItem
                            print("Name of customer: ", strNameOfCustomer)
                            print("Amount sold: ", intItemsSold)
                            print("Cost of one item: ", floatCostOfItem)
                            print("Cost of sale: ", floatCostOfSale)
                            strNameOfCustomer = input("Enter name of customer: ")
                   
                    

Lines 4 - 10 in Listing 4 should be familiar by now and therefore we shall not discuss them. Instead we shall concentrate on lines 2, 3, 4 and 11, i.e. the lines that control the body of the loop.

Line 2 gets the name of a customer from the keyboard and stores it in the variable strNameOfCustomer. Control now passes to line 3. This line could be translated into English as 'while name of customer is not a blank' What this means is that if the user has actually typed in a name then the value stored in strNameOfCustomer cannot be blank. If the user does not want to add any sales data then when they are asked for name of customer they will simply press the Enter key without entering any data. This will cause a blank to be stored in the variable strNameOfCustomer. If this is the case then the test 'while name of customer is not a blank' is false then the body of the loop, i.e. lines 4 - 11 are skipped, thus ending the program.

A typical run through this program would be as follows:

  1. At line 2 the user enters the name 'Tom Thumb' which is stored in the variable strNameOfCustomer
  2. strNameOfCustomer is not blank and therefore the body of the loop is entered.
  3. At lines 4 and 5 values for the amount sold and the cost of one item are entered ans stored in the variables intItemsSold and floatCostOfItem
  4. At line 6 the cost of the sale is calculated
  5. Lines 7 - 10 print out both the values entered by the user and the value that was calculated at line 6
  6. Notice that line 11 is exactly like line line 2 apart from the indentation. Line 2 is executed only once as the first command in the program. On the other hand line 11 is executed once for every iteration of the loop. If the user enters another name then steps 3 - 6 are repeated. On the other hand if the user enters a blank, i.e. presses the Enter key without entering any other data, then the condition at line 3 will be false and the body of the loop will be skipped.

From the above we can deduce that as long as the user continues to supply peoples names when prompted the while loop will keep iterating, but once the user enters a blank the loop terminates.

Fig 1 below shows the running of the program when the user enters a name at line 2 and also enters names twice at line 11.

Fig 1

Again to emphasise that loops usually tend to be parts of a program and not the entire program we show below the same code as Listing 4 but as part of a larger program.

Listing 5
                    
                        #For loop example 1
                        print("This program will collect data about customer sales")
                        print("The data includes customer name, the number of items sold and")
                        print("the cost of one item")
                        print("It will then calculate sales value, and customer total.")
                        print("All data is then printed")
                        print("*******************************")
                        strNameOfCustomer = input("Enter name of customer: ")
                        while strNameOfCustomer != "":
                            intItemsSold = int(input("Enter amount sold: "))
                            floatCostOfItem = float(input("Enter cost of one item: "))
                            floatCostOfSale = intItemsSold * floatCostOfItem
                            print("Name of customer: ", strNameOfCustomer)
                            print("Amount sold: ", intItemsSold)
                            print("Cost of one item: ", floatCostOfItem)
                            print("Cost of sale: ", floatCostOfSale)
                            strNameOfCustomer = input("Enter name of customer: ")
                        print("*******************************")
                        print("The program has now completed its processing")
                        print("If further processing is required the program must be run again")
                    
                    

Fig 2 below shows the running of the code when the exact same values were entered as with Listing 4.

Fig 2
Go to top

Revision

Multi choice

Fill in Blanks

Go to top

Exercises

The exercises below are extensions of their equivalents in the lesson Variables.

Exercise 1

A customer in a store buys a number of the same item. The data required for this transaction are:

Write a program that will allow three customers to be processed. For each customer the program collects the above data from the user, stores each data item in an appropriately named variable and calculates the cost of the sale by multiplying the cost of an item by the number of items sold. It then prints out the data entered by the user as well as the calculated value before processing the next customer. All data must be appropriately labelled. In the case of numeric data ensure that you use integers or floating point numbers correctly.


Exercise 2

Repeat Exercise 1 except that this time an indefinite number of customers must be processed


Exercise 3

Write a program that will collect data about a book. The data required include:

The program must store each data item in an appropriately named variable. Total sales is calculated by multiplying Price by Amount sold. Both the data entered by the user and the calculated values must be printed with appropriate labels.

The program must be able to process four books and the data for one book must be processed and printed out before moving to the next book.


Exercise 4

Repeat Exercise 3 except that this time an indefinite number of books can be processed


Exercise 5

Extend Exercise 3 so that the royalties for the author is calculated. The royalties are calculated as 10% of the total sales. Output must be similar to that for exercise 3 except that the royalties are also included.

Go to top

Assignment

Part 1

You are required to write a program that will collect details about five employees. The program will store each data item in an appropriately named variable. The data required are:

The value for hours worked should be an integer.

Once data entry is complete the Gross Pay is calculated by multiplying Hourly Rate by Hours Worked. Once the value of Gross Pay is calculated, Tax is calculated as 25% of the Gross Pay. Net Pay is calculated by subtracting Tax from Gross Pay. Both input value data and calculated values must be printed with appropriate labels.

Once the current employee is processed the system moves to the next employee until all employees are processed.


Part 2

Repeat Part 1 but this time an indefinite number of employees can be processed

Go to top