for and while loops

You can think of a loop as continuously repeating the same instructions over and over until some condition is satisfied that breaks this loop. For example, the previous code was not a loop; since it was only executed once, we only checked a once.

There are two types of loops in Python:

  • for loops
  • while loops

for loops have a specific number of iterations. You can think of an iteration as a single execution of the specific instructions included in the for loop. The number of iterations tells the program how many times the instruction inside the loop should be performed.

So, how do you create a for loop? Simply, just like this:

for i in range(1, 20):
    print(i)

We initialize this loop by writing for to specify the type of loop. Then we create a variable i, that will be associated with integer values from range (1,20). This means that when we enter this loop for the first time, i will be equal to 1, the second time it will be equal to 2, and so on, all the way to 19. Why 19? That's because in Python, upper bounds are excluded, so at the final iteration i will be equal to 19. As for our instruction, in this case it's just showing the current i in our console by using the print() method. It's also important to understand that the main code does not progress until the for loop is finished.

This is what we get once we execute our code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

You can see that our code displayed every integer higher than 0 and lower than 20.

You can also use a for loop to iterate through elements of a list, in the following way:

L3 = [3,4,1,6,7,5]
for element in L3:
    print(element)

Here we come back to our L3 1D list. This code iterates through every element in the L3 list and displays it. If you run it, you will see all the elements of this array from 3 to 5.

while loops, on the other hand, need a condition to stop. They go on as long as the given condition is satisfied. Take this while loop, for example:

stop = False
i = 0
while stop == False:  # alternatively it can be "while not stop:"
    i += 1
    print(i)
    if i >= 19:
        stop = True

Here, we create a new variable called stop. This type of variable is called a bool, since it can be assigned only two values – True or False. Then, we create a variable called i that we'll use to count how many times our while loop is executed. Next, we create a while loop that will go on as long as the variable stop is False; only once stop is changed to True will the loop stop.

In the loop, we increase i by 1, display it, and check if it is greater or equal to 19. If it is greater or equal to 19, we change stop to True; and as soon as we change stop to True, the loop will break!

After executing this code, you will see the exact same output as in the for loop example, that is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

It's also very important to know that you can stack for and while loops inside each other. For example, to display all the elements from the 2D list L4 we created previously, one after another, you would have to make one for loop that iterates through every row, and then another for loop (inside the previous one) that iterates through every value in this row. Something like this:

L4 = [[2, 9, -5], [-1, 0, 4], [3, 1, 2]]
for row in L4:
    for element in row:
        print(element)

And running this yields the following output:

2
9
-5
-1
0
4
3
1
2

This matches the L4 list.

In conclusion, for and while loops let us perform repetitive tasks with ease. for loops always work on a predefined range; you know exactly when they will stop. while loops work on an undefined range; just by looking at their stop condition, you may not be able to judge how many iterations will happen. while loops work as long as their particular condition is satisfied.

Exercise

Build both for and while loops that can calculate the factorial of a positive integer variable.

Hint: Factorial is a mathematical function that returns the product of all positive integers lower or equal to the argument of this function. This is the equation:

f(n) = n * (n – 1) * (n – 2) *...* 1

Where:

  • f(n) – the factorial function
  • n – the integer in question, the factorial of which we are searching for

This function is represented by ! in mathematics, for example:

5! = 5 * 4 * 3 * 2 * 1 = 120

4! = 4 * 3 * 2 * 1 = 24

The solution is provided in the Chapter 03/For and While Loops/homework.py file on the GitHub page.