All lessons
♾️

While loops

Repeat while a condition holds

Reward
+60 XP

Basic while

while runs the body as long as the condition is True. Update the condition inside the loop or it will run forever.

n = 0
while n < 3:
    print(n)
    n = n + 1

break and continue

Use break to exit early and continue to skip to the next iteration.

n = 0
while True:
    if n == 3:
        break
    print(n)
    n += 1

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • Forgetting to update the loop variable, causing an infinite loop.
  • Using a condition that is never True so the loop never runs.