WHILE

This type of loop repeatedly executes a block of code as long as a given condition remains True. It’s useful when you don’t know in advance how many times the loop needs to run and want the program to keep iterating until something changes inside the loop or an external condition is met. The loop checks the condition before each iteration, and if the condition becomes False, the loop stops. While loops are often used for input validation, counters, and processes that depend on real-time changes. Python also supports optional break and continue statements inside a while loop, giving you control to exit the loop early or skip to the next iteration when needed.

counter = 0
while counter < 5:
    print("The counter is:", counter)
    counter = counter + 1

Last updated