The while Loop#
Learning Objectives#
Understand how to construct and use
whileloopsKnow how to control iterations in a loop
Prerequisites:#
The while Loop#
A while loop is similar to a for loop, with the main difference being it will continuously loop while a condition is True. Where a for loop is used when you know how many times you need to iterate, and a while loop is for when you do not know how many times you need to iterate.
In general, if you could use a for loop, try to do it that way, as while loops have the potential for infinite looping errors to occur if they are not properly controlled (discussed in more detail in the next section).
while loops take the syntax:
while condition:
code block
As as example see the cell below which prints integers from 1 to 5.
count = 0
while count < 5:
count += 1
print(count)
1
2
3
4
5
The first line defines our starting value and the second initiates our loop.
while count < 5:
Looking closer at this line we have:
whilewhich signals we want to start a loopcount < 5is our conditional statement:signals the start of the loop
If our conditional statement is True the code prints out the current value of count and increases it by one for each iteration using the += operator.
Exercise: Use a 'while' loop to print integers
Create a while loop to print even integers from zero to 10.
Click to view answer
count = 0
while count < 11:
print(count)
count += 1
Infinite while loops#
When constructing while loops be wary of your condition, one common bug can be creating a loop that runs forever:
count = 5
while count != 0:
print(count)
count -= 2
In this example, count is never exactly equal to 0: it counts down from 5, to 3, 1, -1, and continues down. As a result, the condition count != 0 is never False, and the loop will run forever.
If this happens, you need to force stop your program. How to do this varies depending on how you run the instrument. In an IDE Look for a little square, it usually represents stopping the program while it is still running. In a terminal press ctrl+c to force stop.
If the program runs for too long without stopping, it could crash your computer.
The simplest kind of infinite loop is this:
while True:
print("This loop will run forever!")
If you start your loop with while True:, that loop will run forever unless a break statement is placed somewhere within it.
Exercise: Debug this infinite loop
This code will run forever, predict why and fix the problem.
answers = [] count = 0 while count < 10: print("Count is:", count) answers.append(count**2) print(answers)
Click to view answer
The problem here is that the count is never increased, and so the code just runs over and over with count = 0. Add the line count = count + 1 into the loop to prevent this.
answers = []
count = 0
while count < 10:
print("Count is:", count)
answers.append(count**2)
count = count + 1
print(answers)
Break and Continue Clauses#
Just like with for loops, we can use break and continue to control a while loop. Particularly useful here is break, as without breaking the loop it becomes easy to make it run forever.
In order to avoid infinite loops, we might want to add a second condition under which the code should stop looping. We can do this using the keyword break.
For example, the code below is the same as the infinite loop example above, but with an additional break added, which will be executed once count < 9. This stops it running forever.
count = 5
while count != 0:
print(count)
count -= 2
if count < -9:
break
With this additional conditional clause, the loop will no longer run forever.
While writing a while loop, it is useful to put a counter and a conditional clause into your loop to ensure it will not run more than a certain number of times, as it is easy to accidentally remove the condition that would otherwise end the loop (for example, in the above code by changing how large the decrease in count it).
Uses of while loops#
while loops are used when you do not know (or do not want to know) how many times a loop will run. This has uses in many areas of programming, for example a loop that must run until the user inputs the correct password, or a video game that must repeat a level until the player defeats the boss.
In scientific programming, we usually know how many times we want a loop to run, so while loops are not very common. However, there are times when we do not know how many times we want the program to run. For example until the uncertainty reaches an acceptable level, until we reach a certain precision (e.g. a certain number or decimal places), or until the program has elapsed a certain amount of time.
Below is one such example. This code scans over a given function to find a local minimum (between a given start and end point). With each loop, the step size decreases by a factor of 10 to give a more precise answer.
# Scan over the quadratic equation y = 5.23x^2 + 2.7x - 1.5 to find the minimum value
# Initial range and step size
start = -100
fin = 100
step = 1
# Loop until the step size is sufficiently small
while step > 0.000000001:
# Identify x values over which to evaluate the function
x_vals = []
for q in range(int((fin - start) / step)):
x_vals.append(start + q * step)
# Evaluate the function at each x value.
y_vals = []
for x in x_vals:
y = 5.23 * x**2 + 2.7 * x - 1.5
y_vals.append(y)
# Find the index of the minimum y value
index = y_vals.index(min(y_vals))
# Print out the minimum y value found and the corresponding x value
print(round(x_vals[index], 10), ",", round(min(y_vals), 10))
# Narrow the range to be around the minimum value found
start = x_vals[index] - step
fin = x_vals[index] + 2 * step # * 2 due to zero-indexing
# Decrease the step size
step = step / 10
The first 5 lines produced by this code read:
0 , -1.5-0.3 , -1.8393
-0.26 , -1.848452
-0.258 , -1.84847028
-0.2581 , -1.8484703597
Each time, the x coordinate gains a decimal place, becoming more precise, and the the y-coordinate approximates closer and closer to the minimum value. This could be used, for example, to find local peaks in spectrum data.
One function in this program you might not have seen before is index(), used here to find the position of the minimum y value. This returns the index of the first occurrence of the specified value. In this case, it is more efficient than enumerate() because we do not care about any of the other values in the list.
Summary#
Whileloops take the syntax:while condition: do action
Whileloops are used when you do not know how many loops you will need.In scientific contexts it can be used to loop until a certain condition is met, for example a certain precision or time elapsed.
You must be careful, as while loops have the potential to loop infinitely without end.
If this happens, you must force-stop your program by either clicking the little square in your IDE, or running
ctrl+cin a command line.
You can control infinite loops using a
breakclause.