Walking Through Loops

Article Info

Last week, I threw a new concept at you at the end of the session. The loop. If you’re used to Python, you might be used to a foreach-style loop (no that’s not a typo, I did call the python for loop a foreach loop).

If you are not familiar with python because you have more of a C#/C++ background that’s ok. The reason I’m using python for this example is because it’s slightly easier to follow. Let’s take a look at the most famous python looping statement:

loop.py
for x in range(0, 10):
    print(x)
print("done")

For reference, this is the same as the C# for loop - although I’m using the python version for this walkthrough - you can find the C# statements later in this lab:

loop.cs
for (int i=0; i < 10; i++) {
    Console.WriteLine("0:D", i);
}

What’s going on here? Although this is the most common way to look at the loop, the loop is actually several statements that are on the same line. Let’s expand these so we can see this more clearly.

loop.py
numbers = range(0, 10) #(1)
for x in numbers: #(2)
    print(x) #(3)
print("done")
  1. Create a list (actually a range) of the numbers 0 to 9

  2. Go through each item in this list (generator) in turn

  3. execute print on each item in this list

What’s this generator thing I keep talking about? That’s very much outside the scope of today’s session. You can think of it as a list where each item only gets built when it’s needed (like I said, out of scope).

(aside) 'out of scope' is an interesting phrase. I guess it was useful to explain 'scope' in the last session, you could think of modules like 'classes' and courses like 'namespaces', then workshops are kinda like 'functions'. This is probably evidence that I need to get out more.

There is actually another level of hiding taking place. That for loop is hiding some additional complexity from us. Let’s expand the code out a bit more.

loop.fakepy
numbers = range(0, 10)

i = 0 #(1)
while i != len(numbers): #(2)
    x = numbers[i]
    print( x )
    i = i + 1 #(3)
print("done")

You can 'think of' a foreach-style loop as a while loop where the incrementing value is hidden.

Walking through our code

Ok, lets 'walk through' this statement together. This is actually a very useful debugging technique I did with some of you last week to help you debug your code.

Ok, 10 is going to be an annoying number to do this with (as the section will become quite repetitive). To make this easier, I’m going to assume we’ll use a range that goes from 0 to 2 (rather than 10):

loop_to_2.fakepy
numbers = range(0, 2)

i = 0
while i != len(numbers):
    x = numbers[i]
    print( x )
    i = i + 1
print("done")

This is the code we’ll now walk through.

Setup (before the loop)

Our program starts the first line creates a variable called numbers and (we pretend) that it a list that contains the numbers 0 to 1 (because range doesn’t include the last number - it’s exclusive). We can think as this as the same as numbers = [0, 1].

Next we set i to be equal to the integer 0.

Variable Value

numbers

[0,1]

i

0

The while loop can be read is, 'if the condition is true, do the stuff in the loop', else jump to the end of the loop.

First iteration

We can look at our table of variable values, we can see that i is 0. The python len function returns the number of items in the list. We know the length of numbers is 2 (because length results the number of items).

Q Is the value of i (0) equal to the length of numbers (2)?

Click to reveal the answer

No

0 is not the same value as 2.

Inside the loop, we use the square brackets [] to figure out the the item in numbers as at the position we put in the brackets (starting at 0). We often see this referred to as the ith value - as we often use i for the variable to iterate the loop.

The thing in location (index) 0 is the number 0. Therefore x becomes 0.

We then print x. At this point in the program, what is the value of x?

We then add 1 to the value of i (0) and then store it, i = i (0) + 1

We reach the end of the loop. x (should) now goes out of scope - in python it doesn’t, but that’s python’s problem.

Variable Value

numbers

[0,1]

i

1

We’re in a while loop, so we jump back to where the while loop was declared.

Second iteration

Ok, we can look at our table of variable values, we can see that i is 1. We know the length of numbers is still 2 (because length results the number of items).

Q Is the value of i (1) equal to the length of numbers (2)? No

Ok, so we enter the loop. Inside the loop we set the value of x to be the ith (1) item of numbers, which is 1. notice i is now 1 so we get a different answer.

We then print x. At this point in the program, what is the value of x?

We then add 1 to the value of i (1) and then store it, i = i (1) + 1

We reach the end of the loop. x (should) now goes out of scope - in python it doesn’t, and that’s still python’s problem.

Variable Value

numbers

[0,1,2]

i

2

Sound a bit familiar?

Third iteration

Ok, we can look at our table of variable values, we can see that i is 2. We know the length of numbers is still 2 (because length results the number of items).

Q Is the value of i (2) equal to the length of numbers (2)? YES

Because the condition is now met, we jump to the end of the loop. This is the statement, print("done"), and indeed we are.

(do you see why I changed that to 2 rather than 10 now?)

Graduation Cap Book Open book GitHub Info chevron-right Sticky Note chevron-left Puzzle Piece Square Lightbulb Video Exclamation Triangle Globe