Loops

Intro to Code A Progress
69%

Now we’re going to review two very useful items in our programming toolbox: while loops and for loops.

The reason loops are called loops is that they do things (run a block of code) over and over again…in a loop! When we want things to happen again and again, we can use two types of loops: while and for loops.

While Loops

While loops are important for doing things over and over again until you reach a point where you want to stop. To put it into plain English, you might say, “while I still haven’t reached a wall, keep moving forward.” If you recall, this could be replicated in Python in Reeborg’s world with the line:

while front_is_clear():
   move()

With just the code above, we would be able to get Reeborg to move all the way across an empty board because he will move until front_is_clear() is false, which is when he hits a wall. After running this loop, the board looks like this:

There are two components of a while loop: the condition, or the question you ask, and the code block, or what you do over and over again (notice that the condition part is similar to the if statement).

Structure of a While Loop

We have the keyword, while, and then a condition (aka a question) we ask, usually with a comparison operator, followed by a colon :.

Inside the loop, we do whatever write the code that we want to run over and over again until the condition we ask isn’t true anymore.

But, now that we know what variables are and how to use them, we can make while loops using variables, too. For example, you could have a while loop that uses a variable you make, called my_number:

# what does this program do?
my_number = 10
while my_number >= 6:
    my_number -= 1

Discuss this with your mentor: What does the above loop do? What is the value of my_number once this program is done running?

For Loops

The second type of loop, as you’ll recall from Reeborg, is the for loop (some of you also used the repeat syntax for this loop in Reeborg, though in Python, you’ll have to use for as the keyword).

When we know how many times we want to do something, we can easily use a for loop that happens again and again until we tell it to stop.

Below, I’ve written the code for the turn_right() function many of you wrote in Reeborg.

for i in range(3):
    turn_left()

Let’s break the for loop down into its components. First, we have the for keyword, which signals that we’re about to enter the loop. Next, we declare a variable that will be used as a “counter” in the loop. The variable we declare here, i, is commonly used for counting and indexing. In Python, the in literally means what you think it does — you are going to make i count up (can also cound down), and each time we loop, we check that i is still a value in that range.

Another important concept is range. The range function takes up to three parameters.

The simplest version looks as follows:

for i in range(number):
   #code block

To make the code in the block run 2 times, we’d use for i in range(2):. To have it run 10 times, we’d use for i in range(100):, and so on…

Structure of a For Loop

We have the keyword, for, and then counter variable (often named i), followed by the keywords in range, and a number as the argument in the parentheses.

The number specifies the number of times the code block inside the loop runs. Implicitly, the for loop adds 1 to the counter variable (or another number if the third argument is specified) each time the code block runs and the for statement checks whether the counter variable is less than the range argument specified. If the comparison evaluates to True, the loop runs again. If the comparison evaluates to False, the loop exits.

Below are the little details of for loops:

Since i is always initialized to 0 in the beginning, for i in range(2):i = 0 before entering the loop. Since 0 < 2, the code inside the for loop runs. Once the loop executes one time, i = 1. Since 1 < 2, the code inside the for loop runs again. Now, i = 2, but 2 < 2 is False, so the loop STOPS.

If we don’t want the i to start from 0, however, we will have to specify the starting number (inclusive) and the ending number (exclusive) we want. These words carry the same meaning when we talk about ranges of numbers in math class. For example, “x is between 10 and 20, inclusive” in a word problem means that x can take on all numbers between 10 and 20, or 10 or 20.

In terms of programming and for loops, inclusive means you want i (the counter variable) to take on this value, while exclusive means that you do not want i (the counter variable) to take on this value; it’ll only include the number before it.
For example, if we specified for i in range(1, 4):, i is assigned to store the value 1 initially and increment up 1 each time, with a final value of 3 when the loop stops, since the second parameter, 4, is exclusive.

The for loop actually takes a third parameter, which is the incrementer. It controls by how much the counter variable increases or decreases on each execution of the loop. For example, for i in range(0, 10, 2): specifies that i is assigned the values 0, 2 (0 + 2), 4 (2 + 2), 6 (4 + 2), 8 (6 + 2), 10 (8 + 2), with each execution of the loop. We can also do super cool things like count backwards, using for i in range(10, -1, -1):, which means i takes on the values 10 down to 0 (recall the first argument is inclusive, the second argument is exclusive, the third argument decreases the value of i by 1 on each execution of the loop).

While Loop vs. For Loop

Discuss this with your mentor the difference between a while loop and a for loop. How are both related to the if statement?

We use while loops when we don’t know how many times for sure, but we know a condition for when we want to stop. If you can say “I want to do something until _____”, there’s a good chance you want to use a while loop.

We use for loops when we know how many times we want to do something.

In some special cases, you can use either kind of loop to solve your probably, but as is the case with many problems, there is often one solution that is more intuitive.