Syncing account progress…

Back

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 -= 1

Output

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

While loops

  1. Identify the condition and the update.
  2. Confirm that the loop will stop.

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.

Practice