For-loop


A for-loop repeats code for a specified number of times. For example, here's the code you could write to print "Python rocks socks!" 100 times:

for i in range(100): 
   print("Python rocks socks!")

What does the i in the for-loop mean?

i is a variable that keeps track of how many times the loop has run. In our loop above, for i in range(100) means that at the start of the loop, i is 0. Each time the for-loop runs, i increases by 1 and keeps going while i is less than 100. Once i reaches 100, the loop stops running.

Here's the equivalent of the for-loop above, written as a while-loop:

i = 0
while i < 100: 
   print("Python rocks socks!")
   i += 1

Now that we know that i is a variable, we can see how we can use the variable i inside our for-loop. Here is a very simple example that demonstrates that point:

for i in range(5): 
   print(i)

When this code is run it will procude the following output:

0
1
2
3
4

Notice how i starts at 0 and doesn't every take on the value 5. That is because i keeps track of how many times the loop has completed. Once the loop has completed 5 times, it is finished! The variable i is an integer, and you can use its value in calculations. For example, here's how we can print even numbers:

for i in range(3): 
   print(i * 2)

Understanding Range

Range is the function which produces the sequence of values that i takes on. For example when we write range(3), it produces the sequence [0, 1, 2]. There are other versions of range if you want to produce other sequences. Range can take in one input, two inputs, or even three:

range(4)        # [0, 1, 2, 3] which is 0 through 4, excluding 4
range(1, 4)     # [1, 2, 3] which is 1 through 4, excluding 4
range(1, 10, 2) # [1, 3, 5, 7, 9] which is 1 through 10, counting by 2s

If we use the version of range with three inputs, we can specify the start, end and step-size. This program prints even numbers 4 through 10:

for i in range(4, 12, 2): 
   print(i)
4
6
8
10

for i in range(4, 12, 2) says: i goes from 4 to 12, exclusive of 12, counting by 2 each time. It doesn't include the final value 12, so the last value i takes on is 10.

Nested Loops

Sometimes you will see for loops put inside other for loops. This is called a "nested" loop. When this happens we refer to the first for loop as the "outer" loop and the second for loop as the "inner" loop. These loops operate much like you would expect. It is very good practice (and quite helpful) to make sure that the index variable is different for each loop. A standard choice is to use i for the outer loop and j for the inner loop. What do you think this nested for loop does?

print('i', 'j')
for i in range(2):
   for j in range(3):
      print(i,j)
This nested loop prints the following to the console:

i j
0 0
0 1
0 2
1 0
1 1
1 2

The outer loop counter, i, takes on the values [0, 1] for each of those values the inner loop counter, j, takes on the values [0, 1, 2].