Many times in programming, you will need to repeat the same task many times. In fact, looping through and repeating an operation is one of the cornerstones of programming. After all, one of the things that computers are way better than humans at is performing repetitive tasks without getting tired or making mistakes.
One of the simplest ways to make a program repeat the same task is to use a
while loop. A
while loop repeats the same block of code while a condition is true. When that condition becomes false, the loop will break, and the regular flow of code will resume.
The structure of a
while loop is similar to what you encountered in the last guide with
if. A while loop begins with the word
while followed by parenthesis containing the condition of the loop and a colon. The following lines are indented and will execute in the loop.
Check out this while loop. Try it yourself in your interpreter to see exactly what it does. You might be somewhat surprised.
# Import time for sleep import time # While loop while(True): print("looping...") time.sleep(2)
What happened? Rather, what is happening? If you haven’t figured out how to stop it yet, just press
while loop will run indefinitely as long as the condition that it is given remains
True. The loop above was given
True as its condition, which will never not be true.