While loops
The next loop we will explore is the while
loop. This type of
loop will continue to execute as long as the specified condition remains
True
. Once the condition evaluates to False
,
the loop terminates. Here is how we can construct it:
while condition:
# run code
# close indent to finish while loop
Similar to the for
loop, the while
loop
commences with the reserved keyword while
. However, instead
of iterating over a defined range of values, it operates based on a
specified condition. The loop continues to execute its block of code
as long as the condition evaluates to True
.
It is akin to an if
statement, but with repeated evaluations
as long as the condition remains true. Therefore, it is essential to
update a value within the while
loop to ensure it
eventually exits; failing to do so can result in an infinite loop!
This makes the while
loop potentially more hazardous
compared to the for
loop and as such
should be used with caution.
Let's now see this type of loop in action, we will replicate the
for (i in 1:5)
loop from the previous lesson
using a while
loop.
In this structure, we first define a starting value with
i = 1
, which will be used to meet the condition set
in the while
loop. As the loop runs, it will print the
current value of i. However, one crucial distinction
from the for
loop is that i does not increment
automatically; we must explicitly increment it within the loop
using i = i + 1
.
You might be wondering about the practical utility of while
loops when for
loops are available. After all, from this
demonstration they are longer to write and more prone to errors.
The while
loops shine in situations where we wish to perform
iterations but the exact number of iterations required is unknown upfront.
They offer flexibility, allowing the loop to run as long as a specific
condition holds true.
Let's see such a scenario in the following example. We set a variable called coffee_beans initially to 100 and then randomly select 1, 2, or 3 and add this to coffee_beans until it reaches a threshold value of 115 while printing out the total sum at each iteration.
Feel free to run the code editor a couple of times to see
that the while
loop will end at different times due
to the randomness in the sampling.
Skipping and exiting while loops
Just like with for
loops, we can use the statements
continue
and break
to skip anything past
the former and exit early with the latter. We update the previous
code to wrap the functionality that adds a random number of beans
into a new function named add_beans
. Additionally,
we've introduced an if statement paired with a continue
statement to skip the printing of the bean count when it falls
between 101 and 105. To enhance our control over the program's flow
further, we've also implemented a break
statement to
terminate the loop prematurely if the number of beans hits or
exceeds 110.
Practice Question
Satella is set to read "Wuthering Heights" by Emily Brontë, a novel that spans across 464 pages. On a regular day, she reads about thirty pages. However, she takes a break every sixth and seventh day to unwind, choosing not to read on these days. Starting from the first day, can you calculate how many days it will take for Satella to finish the novel?
To solve this, you're invited to complete the function
time_to_finish_novel
. For this task, make use of a while
loop, and feel free to utilize the helper function
reading_day
, which returns a boolean indicating whether
Satella is up for reading on a given day. Don't worry about scoring—this
exercise is designed to help you get comfortable with coding.
Further note that this uses the modulo
operator
as well as not
. For a review on those see the operators section.