Press enter to skip the top menu

Python Intermediate

Loops

NCEA Compatibility

Module: as91883 Develop a computer program

Requirements: Iteration, checking input data for validity

Relevant Implications: Error Prevention

Go to top

Learning Outcomes

On completion of this section you will know how to use both for loops and while loops.

Go to top

Introduction

The sequence of our programming has up to now gone from top to bottom. In simple programmes execution started at the first line and continued downwards to the last line.

The introduction of the if..else construct meant that some lines were skipped. If the condition of the if part was false then the body of the if would be skipped and only the body of the else would be executed. Similarly if the condition of the if part was true then the body of the if would be executed and the body of the else would be skipped.

Introducing the if..elif..else construct meant that more lines still would be skipped. In all of this skipping, however, the sequence of the processing was top to bottom and there was no going back.

In loops we interrupt this top to bottom sequence, because the nature of a loop is that a group of lines may be repeatedly executed before the line following them gets executed. Thus a sequence of execution of a group of lines containing a loop could be:

1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 6, 7, 8

Here we notice that the lines 3, 4, 5 are executed 5 times before line 6 is executed. This means that those lines are part of a loop. Here we shall look at two types of loops: for loops and while loops.

Go to top

For Loops

Of all the mainstream computing languages Python has the largest number of variations on the for loop. The control line of the loop has the structure

For variable in container

Container is usually a range of numbers, a list or string value.

The body of the loop starts by variable taking the value of the first element in the container and doing some processing on it. Once processing is complete it takes the value of the second element and so forth until all of the elements in the container have been processed

Below we examine five variations of the for loop.

Listing 1
                    
                        #C7 For Loop range
                        for intLoopCounter in range(5):
                            print(intLoopCounter, intLoopCounter*intLoopCounter)
                    

In Listing 1 the control line of the loop is at line 2. Here the variable is intLoopCounter and the container is range(5). This means that the variable intLoopCounter will take values 0, 1, 2, 3, 4. The value 5 is the upper limit of the range and is not actually included

Notice also that line 2 ends with a colon, which means that line 3 is the body of the loop or that in other words line 3 is subservient to line 2.

Once control passes to line 3 the variable intLoopCounter takes on the value of the first element in the range, i.e. 0 and then prints that value along with its square. Thus it prints 0 0

The variable intLoopCounter then takes the value of the second element, i.e 1 and then prints it and its square: 1 1

Next it takes the value of the third element, i.e. 2 and prints it and its square i.e. 2 4

This continues until the number 4 is processed. After this the processing of the loop stops because the upper limit, i.e. 5 in this case, is not actually part of the range.

In this example only one parameter was passed to the function range(): the value 5. When it is passed only one value, the function range() makes the following presumptions:

The output from the code is shown in Figure 1 below.

Fig 1
Listing 2
                    
                        #C7 ForLooprange1
                        for intLoopCounter in range(5, 10):
                            print(intLoopCounter, intLoopCounter*intLoopCounter)
                    
                    

In Listing 2 the container is now designated as range(5, 10). Here 5 is the lower limit and 10 is the upper limit. When both lower and upper limits are stated then the lower limit is included in the range but the upper limit is excluded from it. This means that in this case the values that the variable intLoopCounter will take on will be 5, 6, 7, 8 and 9.

With no other value supplied, an increment of 1 is presumed.

The output is shown in Figure 2 below.

Fig 2
Listing 3
                   
                        #C7 ForLooprange2
                        for intLoopCounter in range(5, 10, 2):
                            print(intLoopCounter, intLoopCounter*intLoopCounter)
                    
                    

In listing 3 the container is designated as range(5, 10, 2). As before 5 is the lower limit, 10, is the upper limit and 2 is known as the step. As before 5 is included in the range but 10 is excluded from it. The step, i.e. 2 in this case, determines the increment that the variable intLoopCounter goes through until it either reaches or exceeds the upper limit. In this case the values for intLoopCounter will be 5, 7 and 9. This is shown in Figure 3 below.

Fig 3
Listing 4
                        #C7 ForLooprange3
                        for intLoopCounter in range(10, 5, -1):
                            print(intLoopCounter, intLoopCounter*intLoopCounter)
                    

In Listing 4 the container is now designated as range(10, 5, -1). This means that the starting value is 10, the finishing value is 5 and that the step is -1. We are now counting backwards. As in all of the cases before the finishing value is not included in the range and thus the values that the variable intLoopCounter will take on will be 10, 9, 8, 7, 6 as shown in Figure 4 below.

Fig 4
Go to top

While Loops

A simple Example

Although the while loop repeats a number of lines just as the for loop does, their structure and functions are very different. The main difference between the two loop types is that we always know how many times a for loop will iterate, whereas we don’t ever know how many times the while loop will iterate. One of the reasons for this is that it often depends on direct data input from the user. Our two examples for a while loop demonstrates this.

Listing 5
                        
                            #C7 While Loop 1
                            floatValue=float(input("Enter a value between 5 and 20:  "))
                            while (floatValue <5 or floatValue > 20):
                                print('Values entered must be in the range 5 - 20')
                                floatValue=float(input("Enter a value between 5 and 20:  "))
                            print("The value entered was " + str(floatValue))
                        
                    

Listing 5 contains our first example of a while loop. This an example of a loop that restricts the values a user can enter to numbers in the range 5 to 20 inclusive.

Line 2 should be familiar by now. It simply accepts numeric input from the user and stores it in the variable floatValue. The body of the loop follows next and spans lines 3 to 5. Line 3 is the controller of the loop. It starts with the keyword while. The keyword is followed by the loop condition which is floatValue being either less than 5 or greater than 20. Thus any of the following values would make the condition true: 4, 1 0 -5, 21, 28, 165. Conversely any of the following would make it false 5, 9, 16, 20. Also notice that the condition is followed by a colon, indicating that the line or group of lines following are subservient to line 3. Since both lines 4 and 5 are indented they form the body of the loop. Now let us go through the programme and see how the loop controls what data the user can enter.

At line 2 the user is prompted to enter a value. If they enter 2 then this is converted to a floating point number and stored in floatValue. Now programme control passes to line 3, where we meet the header of the loop. Of the two sub-conditions following the while keyword, floatValue < 5 is true since 2 is less than 5 and the other condition is false. As we need only one of the sub-conditions to be true it means that the entire condition is true. For this reason the body of the loop is entered.

Within the body of the loop line 4 causes the information item ‘Values entered must be in the range 5 to 20’ to be displayed on the screen and then control passes to line 5 where the user is prompted once more to enter a value.

If the user enters a value of 21 then this is converted and stored in floatValue as before. We have reached the end of the body of the loop by now and therefore control passes back to line 3 where floatValue is tested once more. This time the first sub-condition will be false since 21 is not less than 5 but the second sub-condition, floatValue>20 will be true since 21 is greater than 20.

Since one of the sub-conditions is true the entire condition is true and thus the body of the loop is entered for the second time. The information message is printed as before and the user is prompted again to enter a value.

This time suppose the user enters 15, then when control passes back to line 3 floatValue is tested again. This time both of the sub-conditions will be false since 15 is not less than 5 and also it is not greater than 20. Since the two sub-conditions are false the entire condition is false. Thus the body of the loop is skipped and control passes to line 6 where the validated value is printed on the console.

Now let us have one more look at the structure of the while loop. Notice that it has two near-identical lines where data is read: line 2 and line 5. The only difference between the lines is that line 3 is flush with the left margin, whereas line 5 is indented.

Line 2 is executed only once, which is just before the loop is encountered. It gets the user’s first attempt to enter data. At line 3 this data is tested. If it is faulty, i.e. if one of the sub-conditions is true then the body of the loop is entered. Once the error message is printed the user must be able to enter another value. As we cannot go back to line 2 because it is outside the confines of the loop we must have another input line at line 5. Since this is the end of the loop body control can go back to line 3 where the new value is tested again. Thus the programme can loop around lines 3 to 5 as long as is necessary until both of the condition at line 3 is false.

Figure 6 below shows a sample output from the programme.

Fig 5

Extending our Payroll Application

Here we reintroduce our payroll application and demonstrate how we can use while loops to validate data coming into the program.

Listing 6
                    
                        #C7 While Loop Payroll
                        floatHours=float(input("Enter hours worked:  "))
                        while(floatHours < 5 or floatHours > 60):
                            print("Hours must be in the range 5 - 60")
                            floatHours=float(input("Enter hours worked:  "))
                        floatRate=float(input("Enter hourly rate:  "))
                        while(floatRate < 15 or floatRate > 100):
                            print("Rate must be in the range 15 - 100")
                            floatRate=float(input("Enter hourly rate:  "))
                        floatGross=floatHours * floatRate
                        floatTax=floatGross * 0.25
                        floatNet=floatGross-floatTax
                        print("Gross is " + str(floatGross))
                        print("Tax is " + str(floatTax))
                        print("Net is " + str(floatNet))
                   
                

Listing 6 above, although containing no new code, shows a more practical application of the while loop. Lines 2 to 5 control the input of a value for floatHours which is validated to be be in the range 5 to 60. Similarly lines 6 to 9 control the input of the hourly rate, which is validated to be in the range 15 to 100. The rest of the code should be familiar to you by now.

Figure 7 below shows a sample output from the programme.

Fig 6

Go to top

Summary

Loops

for loops

We know exactly how many times a for loop will run

The specifications for its running are in the range()

On this page we looked at four versions of the loop

A single value in the range()

for intLoopCounter in range(5):

Here intLoopcounter iterates through the values 0, 1, 2, 3 and 4

The lower limit is always presumed to be zero and the increment is presumed to be 1

The upper limit 5 is not used

Two values in range()

for intLoopCounter in range(5, 10):

The first value in range() is the lower limit and the second value is the upper limit

Here intLoopcounter iterates through the values 5, 6, 7, 8 and 9

The lower limit is used but again the upper limit 10 is not used

The increment is still presumed to be 1

Three values in range()

for intLoopCounter in range(5, 10, 2):

The third argument here, 2, is the increment

Here intLoopcounter iterates through the values 5, 7, and 9

The lower limit is used but the upper limit is not used

Three values in range()

for intLoopCounter in range(10, 5, -1):

the start and end numbers are in reverse order and the increment is negative

This means we are counting backwards

Here intLoopcounter iterates through the values 10, 9, 8, 7 and 6

Again the limit indicator 5 is not used

Go to top

Practice

Take each of the examples of the for loop and copy the code into a .py file. then save and run it. Next change the parameters to the range function and check the output.

As an example for this, in Listing 1 change range(5) to range(3), range(7) etc. Copy the code in Listing 5 into a .py file and run it. Once it is running satisfactorily modify line 3 to change the upper and lower limits of the variable floatValue and again test the programme to ensure that only values within the new limits are allowed and values above or below those limits are rejected.

Go to top

Revision

Multi choice

Fill in the blanks

Go to top

Exercise

In the following code snippets state what the lowest value, highest value and step are for the for loop: range(10), range(10,15), range(5,10,2), range(10,2,-2)

Go to top

Assignment Part 3

Modify the code you created for Assignment Part 2 so that the discount code is validated as being in the range 1 to 4.

Go to top