Loops

For loops While loops Summary Practice Exercise Assignment 4

Learning Outcomes

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

Download pdf version

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

Go to top

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

1

#C7 ForLooprange

2

for iterateVar in range(5):

3

    print(iterateVar, iterateVar*iterateVar)

 

In Listing 1 the control line of the loop is at line 2. Here the variable is iterateVar and the container is range(5).  This means that the variable iterateVar will take values 0, 1, 2, 3, 4.  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 iterateVar 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 iterateVar 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:

·         that it has been passed the upper limit of the range

·         that the lower limit is zero

·         that the step or increment is 1, i.e. that the  values assigned to the counter will increase in steps of 1.

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

Figure 1

Listing 2

1

#C7 ForLoopRange1

2

for iterateVar in range(5,10):

3

       print(iterateVar, iterateVar*iterateVar)

 

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 iterateVar will take on will be 5, 6, 7, 8 and 9. 

When the function range() is passed two parameters, Python presumes the first parameter to be the lower limit of the range and the second parameter to be the upper limit.  Again an increment of 1 is presumed.

The output is shown in Figure 2 below.

Figure 2

 


Listing 3

1

#C7 ForLoopRange2

2

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

3

       print(iterateVar, iterateVar*iterateVar)

 

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 iterateVar goes through until it either reaches or exceeds the upper limit.  In this case the values for iterateVar will be 5, 7 and 9.  This is shown in Figure 3 below.

Figure 3


Listing 4

1

#C7 ForLoopRange3

2

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

3

       print(iterateVar, iterateVar*iterateVar)

 

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 iterateVar will take on will be 10, 9, 8, 7, 6 as shown in Figure 4 below.

Figure 4


Listing 5

1

#C7 ForLoopList.py

2

listVeggies=['Carrot','Potatoe','Kumara','Cabbage','Broccoli']

3

for strVeggie in listVeggies:

4

       print(strVeggie)

 

In Listing 5 we get away from the range function since this time we have a list containing  the names of five vegetables.  In line 3 the variable strVeggie takes the value of the first element of the list, i.e. ‘Carrot’ and prints that value at line 4.  After this it takes on each other element of the list in turn, including ‘Broccoli’ and prints them.  Thus when the container is a list all elements, including the last one, are processed.  The result is shown in Figure 5 below.

Figure 5

While Loops

Go to top

Although the while loop repeats a number of lines indefinitely 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 6

1

#C7 While Loop 1

2

floatValue=float(input("Enter a value between 5 and 20:  "))

3

while (floatValue<5 or floatValue>20):

4

    print('Values entered must be in the range 5 - 20')

5

    floatValue=float(input("Enter a value between 5 and 20:  "))

6

print("The value entered was " + str(floatValue))

 

Listing 6 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 – 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 – 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 he enters 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 – 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, wheras 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 – 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.

Figure 6

Listing 7

1

#C7 While Loop Payroll

2

floatHours=float(input("Enter hours worked:  "))

3

while(floatHours<5 or floatHours>60):

4

    print("Hours must be in the range 5 - 60")

5

    floatHours=float(input("Enter hours worked:  "))

6

floatRate=float(input("Enter hourly rate:  "))

7

while(floatRate<15 or floatRate>100):

8

    print("Rate must be in the range 15 - 100")

9

    floatRate=float(input("Enter hourly rate:  "))

10

floatGross=floatHours * floatRate

11

floatTax=floatGross * 0.25

12

floatNet=floatGross-floatTax

13

print("Gross is " + str(floatGross))

14

print("Tax is " + str(floatTax))

15

print("Net is " + str(floatNet))

 

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

Figure 7 below shows a sample output from the programme.

Figure 7

Summary

Go to top

We have looked at two types of loops, for loops and while loops. They are similar in that they repeat a group of lines a number of times.  Apart from that they are quite different.  In general a for loop goes through a definite number of iterations whereas a while loop goes through an indefinite number of iterations, including zero.

Practice

Go to top

1.      Take each of the examples of the for loop copy the code into a .py file 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.

2.      Copy the code in Listing 6 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.

Exercise

Go to top

1.      In the following code snippets state what the lowest value, highest value and step are for the for loop:

a.       range(10)

b.      range(10,15)

c.       range(5,10,2)

d.      range(10,2,-2)

Assignment Part 4

Go to top

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