Sometimes you want to repeat code but not a fixed number of times.
A while loop runs a block of code and repeats it as long as a condition is true.
while run_condition:
#do something
For example, the following code will print the numbers 10 to 1.
x= 10
while x > 0:
print(x)
x -= 1
This loop will continue to run until the user inputs a positive number:
number = int(input("Enter a positive number"))
while number <= 0:
number = int(input("Enter a positive number"))
Note: A while loop will not run at all if the condition is False the first time checked.
Note: The run condition is only checked at the beginning of each iteration. If the condition becomes False in the middle of the code, then True again by the end of the body, the code will continue to run.
Some while loops are intentionally made infinite by setting the run condition to True. These will run until something else ends the loop or ends the program.
Be aware that it's easy to accidentally design a loop that's not intended to by infinite, but becomes infinite because its run condition is always True.
The break command will end the innermost loop. (This also works in for loops.)
A "Loop-And-A-Half" is a while loop that, instead of a condition to run, runs an infinite loop that will break under certain conditions.
Normal while Loop
while run_condition:
#do something
Loop-And-A-Half
while True:
#do something
if termination_condition:
break
Generally a normal while loop is better in terms of readability, but Loop-And-A-Half can be better if you need to terminate in the middle of an iteration.
When you're iterating a fixed number of times, or iterating through an iterable, use a for loop.
If how many times you're looping is uncertain and determined by a condition, use a while loop.