Similarly to for loops, a while loop repeatedly executes all the statements within its scope. However, the amount of times a while loop runs is not determined by a set number as it is in for loops. Instead, the amount of times a while loop runs depends on a conditional.
ie. a while loop repeatedly executes all the statements within its scope as long as the loop conditional remains true
Important Note: Since while loops continue until their condition is false, it's important to make sure that the condition will become false at some point! Otherwise, you will enter an infinite loop!
If you're not sure exactly what this means, don't worry!
To the right is a short video to help you understand by providing some examples:
And below is an example of some code using a while loop. Run the cell to see the output!
Now, try to modify the code above to count down from 10 instead of counting up to 10!
Coding Assistance: Click this link if you need help solving this problem.
Just like with for loops, we can use break statements within while loops to exit the loop prematurely
ie. to break the loop, even if the original condition is still true!
See the video below for an example of when this might be useful!
The following code has a mistake - can you help find it?
The desired output is:
i = 0
i = 1
i = 2
i = 3
i = 4
If you run the code below, you will see this is not the actual output.
Try to update the code to fix this!
Answer: The issue behind this loop is that we never update the value on which the conditional is based, meaning we never update the value of i! Since i isn't changing, it will never grow to be larger than 5, so the conditional (i<5) will always be true. Therefore, we have accidentally created an infinite loop!
To fix this, we can simply add a line "i+=1" after the print statement (still indented under the while loop). Try it and see!
The video to the left shows an example of how we can break out of an otherwise infinite loop using break statements!