Python For GCSE
While loops are used for conditional iteration. That means that the number of repetitions can vary depending on a specific condition.
We could use a while to get the same behaviour as we would from a for loop, it just isn't as convenient to do.
x = 0 while x<10: print(x) x = x + 1
More often than not, we want to repeat until a condition is no longer satisfied.
x = 0 while x==0: x = int(input("Enter a number other than 0: ")) print("Your non-zero number is", x)
You can use break and continue statements inside while loops the same way that you do with for loops.
Pre-Tested & Post-Tested Loops
The while loop is a pre-tested conditional loop. That means that the condition is examined before each iteration.
A post-tested loop has the condition examined at the end of each iteration, rather than the start. This means that there would always be at least one iteration. Unlike some languages, Python does not have a separate structure for this. If you look at the second example on this page, it achieves a similar effect to a post-tested loop. The variable x is set to ensure that at least one iteration takes place.