Equivalent Loops

3.15. Equivalent Loops#

When programming, you’ll find that there are often multiple ways to write your program and have it do the same thing! Have a look at the examples below. You will find that in each example, the programs do the exact same thing.

Example 1: Count 0 to 4

i = 0
while i < 5:
    print(i)
    i = i + 1
0
1
2
3
4
for i in range(5):
    print(i)
0
1
2
3
4
../../_images/9_example1.png

Example 2: Print each colour

colours = ['red', 'green', 'blue', 'yellow']
i = 0
while i < len(colours):
    print(colours[i])
    i = i + 1
red
green
blue
yellow
colours = ['red', 'green', 'blue', 'yellow']
for i in range(len(colours)):
    print(colours[i])
red
green
blue
yellow
colours = ['red', 'green', 'blue', 'yellow']
for i in colours:
    print(i)
red
green
blue
yellow
../../_images/9_example2.png

When you write a loop you will have to choose whether you use a for loop or a while loop. Often, it won’t matter which one you choose as both will work. But in general, you would use:

  • a while loop if you don’t know how many times to repeat your code - instead, you will terminate your loop once a certain condition is met

  • a for loop if you know how many times you want to repeat your code

Question 1

Which of the following while loops produces the same output as the for loop shown below?

for i in range(5, 10):
    print(i)
  1. i = 0
    while i < 10:
        print(i)
        i = i + 1
    
  2. i = 5
    while i < 10:
        print(i)
        i = i + 1
    
  3. i = 0
    while i < 10:
        print(i)
        i = i + 5
    
  4. i = 1
    while i < 10:
        print(i)
        i = i + 5
    
Solution

B.

This for loop counts from 5 up to but not including 10. To construct an equivalent while loop, we want i to start at 5 and then increase by 1 at each iteration until it also goes up to but does not include 10. Of the options provided the second one is the only one where i starts at 5.

../../_images/9_question1.png
Question 2

Will the following two programs produce the same output?

Program 1

words = ['rain', 'one', 'light', 'owl', 'ranch']
for i in range(len(words)):
    print('b{}'.format(words[i]))

Program 2

words = ['rain', 'one', 'light', 'owl', 'ranch']
for i in words:
    print('b' + i)
Solution

Solution is locked

Question 3

Construct a for loop that is equivalent to the following while loop.

fries = ['curly', 'shoestring', 'waffle', 'crinkle', 'wedge']

i = -1
while i > -len(fries):
    print(fries[i])
    i = i - 1
Solution

Solution is locked