Loops are used to iterate through the same block of code multiple times. A
for loop will keep executing the same block of code until it has iterated through the entire iterable (list, dictionary or tuple).
while loops are different than
for loops. A
while loop will keep running a block of code repeatedly until a specified condition becomes
False. The skeleton for a
while loop is as follows:
while (condition): //execute code
In this article, you're going to learn how to use while loops to repeatedly execute a block of code based on a condition.
While loops in action
You will start by defining a
while loop that keeps printing a random number while the random number remains less than 30
random_number = 25 while random_number < 30: print(random_number)
The code runs forever! Stop the code's execution from the Runtime menu.
The code runs forever because the while loop is configured to keep running while random_number is less than 30. The condition
random_number < 30 will always be
random_number will always be equal to 25.
This can be fixed by incrementing
random_number by 1 in each iteration.
while random_number < 30: random_number += 1 print(random_number)
In each iteration,
random_number is incremented by 1 until it reaches 30.
random_number eventually becomes large enough to render the condition
False, breaking the
That wraps it up for
while loops. They are as simple as they seem!
In summary, a
while loop will repeatedly execute a block of code until its condition stops being met. Try playing around with the condition and see what type of results you get!