The while loop in Python is used when you want an operation to be repeated as long as a specified condition is met.
The While loop is used to iterate (repeat) part of the program several times. If the number of iterations (repetitions) you want to perform is not fixed, it is recommended to use a While loop. Generally, we can imagine the While loop as a repetition of one or more sequences that occur as long as one or more conditions are met.
The image to the right (same as the introduction, press for larger) shows the flow chart for how the while loop works.
while condition: should happen within the loop
All code indented after the while command will execute if the condition is True
We’ll see a simple example of how we can use the while loop to perform an operation while the specified condition is met.
After that we create our while loop.
i = 0 while i < 5: print(i) i = i +1 # add 1 to the variable i
In this example, we print the value for the variable i as long as the condition is met. In other word, as long as i is less than 5. The program will thus print the value five times and then end the while loop. The result is
0 1 2 3 4
Note, what had happened if i ++ had not been in the loop? Exactly, the condition for the loop will always be fulfilled (zero is always less than five) and the while loop will not end.