7. Fixed Loops

In the previous lesson we studied conditional loops. Now it is time to see fixed loops.

What's the difference?

With a fixed loop, you know how many times you are going to repeat the loop in advance. This is not the case with conditional loops as you have seen.

Run this code. It should produce 5 stars, each on a separate line.
Then change it to produce just 3 stars, each on a separate line.


In [ ]:
for star in range(5):
   print("*")

If you've done it right, your output should now look like this:

*
*
*

The function range() will produce a series of numbers for you, starting with zero by default.
Technically, range(n) produces a zero indexed iterator 0,1,2,..,n

Run this code to produce a count from zero to four:


In [ ]:
for number in range(5):
    print(number)

The variable number is called a 'dummy variable'. It's not that we are insulting it, rather think of number as a placeholder. In the copy of the same loop below, you should change both instances of number to a variable name of your own choice. I recommend beeblebrox, but it's up to you. Make sure the code still works as before.


In [ ]:
for number in range(5):
    print(number)

Ranges can start with other numbers, but stop before the second number.

Run this code to obtain a list from 10 to 19


In [ ]:
for number in range(10,20):
   print(number, end=' ')

You should now change the following program so that is shows a list of the numbers from 20 to 39.
Please see how we now put a comma after each number as well as a space.


In [ ]:
for number in range(10,20): #change the range!
   print(number, end=' ')   #change the end to end=','

If you've done it right, your output should now look like this:

20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,

Ranges can go up (or down) by different numbers.

Run this example to produce the first few odd numbers.


In [ ]:
for number in range(1,20,2):
   print(number, end=' ')

Alter this code to produce the stations of the 6 times table:


In [ ]:
for number in range(0,73,3):
    print(number, end=' ')

If you've done it right, you should have the following output:
0 6 12 18 24 30 36 42 48 54 60 66 72

Python range() function can also count backwards, of course.

for number in range(10,0,-1):
    print(number)

Output will be 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 (without the commas). Notice this does include 10, but doesn't include 0

You can now complete programming tasks 21-23, task 26, tasks 30-31
Leave 24, 25, 27, 28, and 29 for now.