Python · Beginner · 10 min
While loops
Repeat a block while a condition stays true.
Repeat while a condition holds
A while loop checks its condition before each repetition. Update a value so the condition eventually becomes false; otherwise the loop may never end.
remaining = 3
while remaining > 0:
print(remaining)
remaining -= 1Output
3 2 1
Check before running
If the condition is false at the start, the body does not run. A line after the loop runs when the loop ends. -= subtracts from the current value.
remaining = 0
while remaining > 0:
print("Working")
remaining -= 1
print("Finished")Output
Finished
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Count down
Keep the initial remaining value as 3. Use a while loop to print 3, 2, and 1, then print Go after the loop.
Print the current value, then subtract one inside the loop.
While loops
- Identify the condition and the update.
- Confirm that the loop will stop.