Lesson 03-06: Iterating Over a Range

Learning Target: I can use for loops to iterate over a range of numbers.

Now that we’ve covered the range() function, what about the rest of the for loop?

An example of a for loop is: for x in range(5): - what does the x mean?

for Loop Syntax, Extended

The for loop syntax can be written as follows: for item in iterable:.

  • iterable is something that is capable of returning its members one at a time, such as a range.
  • item is each member returned from the iterable.

Take the example:

 
1
for x in range(3):
2
    print(x)
3
0
1
2

(0306_ex_1)

We know that range(3) represents a list of numbers [0,1,2]. When this for loop loops 3 times, each time, x will take on the next value from range(3), starting at the beginning.

This is why the 0 gets printed out, then the 1, then the 2. First x takes a value of 0, then x takes a value of 1, then x takes a value of 2.

Additional Notes:

The variable can be named whatever you want too. Just make sure it doesn’t conflict with any other variable, or it will overwrite it.

3
 
1
for number in range(5):
2
    print(number)
3
0
1
2
3
4

(0306_ex_2)

The variable can be used just like any other variable as well.

5
 
1
for number in range(5):
2
    print("the number is {}".format(number))
3
    number = number * 10
4
    print("ten times the number is {}".format(number))
5
the number is 0
ten times the number is 0
the number is 1
ten times the number is 10
the number is 2
ten times the number is 20
the number is 3
ten times the number is 30
the number is 4
ten times the number is 40

(0306_ex_3)

Remember, this works for any range as well!

4
 
1
for num in range(5,0,-1):
2
    print("T-{}...".format(num))
3
print("Blastoff!")
4
T-5...
T-4...
T-3...
T-2...
T-1...
Blastoff!

(0306_ex_4)

Checks For Understanding

Q#1

Write a program that will print out the first 10 multiples of 3. In the end you will know if you got it right if you printed out the following numbers, one per line: 3,6,9,12,15,18,21,24,27,30.

2
 
1
#write your code here!
2

(0306_cfu_1)

Q#2

Write a program that will print out a countdown from 5 to 0, then prints back the same numbers up to 5, counting up. Here is what the output should look like:

5
4
3
2
1
0
1
2
3
4
5

You may use more than one for loop.

2
 
1
#write your code here!
2

(0306_cfu_2)

Q#3

Write a program that will print out the numbers from 1 to 10 inclusive, but if the number is divisible by 4, it will print (“<num> is divisible by 4”). Here is what the output should look like:

1
2
3
4 is divisible by 4
5
6
7
8 is divisible by 4
9
10
2
 
1
#write your code here!
2

(0306_cfu_3)

Next Section - Lesson 03-07: Accumulator Algorithms