while loops, explained simply
A for loop repeats a set number of times. A while loop repeats for as long as a question stays True. It is perfect when you do not know in advance how many repeats you need.
Before each repeat, Python checks the question. If it is True, the indented lines run. If it is False, the loop ends and the program moves on.
Something inside the loop must eventually make the question False, or the loop will never stop. That is called an infinite loop, and every programmer writes one by accident sooner or later.
Example: Count down to launch
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Lift off!")Output
3
2
1
Lift off!Try this
- Start the countdown at 10.
- Write a loop that keeps asking "Password?" until the person types the right one.
- Delete the line that subtracts 1 and see what happens. (Stop the program if it runs forever.)
