5.4. While Loops#

In the last section, we saw examples where we wanted to repeat a process a known number of times. However, it could be the case that we don’t know exactly how many times we want to repeat something. This is a situation where we might want to use a while loop.

In a while loop, the body of the loop will be executed as long as, or while a specific condition is true.
The general format of a while loop is below.

while condition:
    action  

Notice, we do still see the colon and the indented body in the format of a while loop, and we have the keyword while to initiate the loop.

To illustrate the main idea of a while loop, consider the example below. Here we initiate a value for a, and then the condition a < 4 is evaluated. If this Boolean output is True, the body of the statement will execute. In this case we update a during each iteration. Once a = 4, the condition a < 4 is False, thus the loop is no longer executed.

a = 0

while a < 4:
    a = a +1 
    print(a)
1
2
3
4

Notice a key difference between an if statement and a while loop in the example below. An if statement will execute exactly once, whereas a while loop will execute an unknown number of times, as long as the given condition is True.

a = 0

if a < 4:
    a = a +1 
    print(a)
1

What might be a situation where we don’t know how many times we want to repeat something? The simulation below considers such an example.

Simulation with the while loop#

Suppose we have a six-sided die and we want to know how many rolls until we get a 5? We can simulate this with a while loop.

First creating our six-sided die, we want to continue rolling while the statement I have not rolled a 5. is True. We do this by creating a list of stored rolls list_of rolls and checking if the number 5 is contained in that list. This condition becomes the while loop condition.

while 5 not in list_of_rolls

Each iteration, we roll the die again and store the new output. As soon as 5 not in list_of_rolls is False, we have rolled a 5, so we are done.

die = np.arange(1, 7)
list_of_rolls =[]

while 5 not in list_of_rolls:
    list_of_rolls.append(np.random.choice(die))
    
print(list_of_rolls)
[5]

How many rolls until we got a 5? We could directly count the output above, but in general we can call the len function.

len(list_of_rolls)
1

Repeating this experiment gives us an idea of how many rolls we need, on average, before rolling a 5.

Below we run 100 experiments, where each iteration we collect how many rolls were needed before getting an output of 5.

how_many = np.array([])

for i in np.arange(100):
    list_of_rolls =[]

    while 5 not in list_of_rolls:
        list_of_rolls.append(np.random.choice(die))
    how_many = np.append(how_many,len(list_of_rolls))
    

Finding the average of the how_many array tells us we need approximately 6 rolls of the die before we get a 5.

how_many.mean()
5.57

Note

This is an example of simulating under the geometric distribution, where we are interested in the number of trials before the first success.

Infinite loops#

Note of caution. Since we do not specify a number of iterations for a while loop, there is a possibility of entering an infinite loop. This is a situation where your condition is always met, and never False, meaning the while loop will never terminate naturally - but rather will terminate when it runs out of memory or time.

In the example below, we see the condition x > 0 is always True, thus you might get a Timeout Error when running the code.

x = 3

while x > 0:
    print(x)
   

Usually the body of the statement would contain some way to update the condition parameter, in this example the value of x, so that there is an opportunity for the truth value of the condition to change.

If we are concerned about an infinite loop possibility, we can use a break inside of a while loop. This allows us to terminate the while loop after a fixed number of iterations or some predetermined condition. The first time the break statement is reached, the while loop will immediately terminate.

x = 3
count = 0

while x > 0:
    count = count +1
    print(count)
    if count > 5:
        break
1
2
3
4
5
6

In addition to a simulation example where we want to repeat a process an unknown number of times, while loops are also useful when asking for programs involving user input. If we prompt a user to enter their age as an integer value, we don’t know how many times they could incorrectly input a value. Until the input is as expected we would continue to prompt the user for a valid response.