Python

While Loops

YouTube

While loops in Python are a type of control flow statement that allow you to execute a block of code repeatedly, as long as a certain condition is met. They are useful when you want to perform an action an unknown number of times, or until a specific condition is met.

To create a while loop in Python, you use the while keyword followed by a condition, and then a colon. The code block that follows is indented, and it is the block of code that will be executed repeatedly as long as the condition is True.

While Loop

Here is an example of a basic while loop in Python:

count = 0
while count < 5:
  print(count)
  count += 1

In this example, the while loop will continue to run as long as the value of the count variable is less than 5. The count variable is incremented by 1 each time the loop runs, so the loop will eventually terminate once the count variable reaches 5.

There are a few things to keep in mind when using while loops in Python. First, it is important to make sure that the condition being checked is eventually going to be False, or the loop will run indefinitely and create an infinite loop. You can avoid this by including a statement within the loop that will eventually change the condition to False.

Make sure there is a way for the while loop to end, having an infinite loop will cause your script to continue to run until it is forced quit. Most computers will be able to put up with this, but if you’re a beginner it’s best not to try it just incase!

Break and Continue

You can also use the break keyword to exit a while loop prematurely if a certain condition is met. This can be useful if you want to exit the loop once a specific task has been completed.

Finally, you can use the continue keyword to skip the rest of the code block and move on to the next iteration of the loop. This can be useful if you want to skip certain iterations of the loop based on a certain condition.

count = 0
while True:
    count += 1
    if count == 3:
        continue
    print(f"{count}, Still True")
    if count == 6:
        break

# Outputs 
# 1, Still True
# 2, Still True
# 4, Still True
# 5, Still True
# 6, Still True