Lesson 59 +10 XP

While Loops

While Loops

A while loop repeats as long as its condition is true.

The basics

i = 1
while i < 6:
    print(i)
    i += 1

This prints 1, 2, 3, 4, 5. The loop stops when i reaches 6.

Infinite loop warning

If you forget to change i, the loop never ends:

while i < 6:
    print(i)  # runs forever!

Always make sure something changes the condition.

break

break stops the loop immediately:

i = 1
while i < 6:
    print(i)
    if i == 3:
        break
    i += 1
# prints 1, 2, 3

continue

continue skips the rest of the block and jumps back to the condition:

i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i)
# prints 1, 2, 4, 5, 6 (skips 3)

else on a while loop

The else runs when the condition becomes false (but not after break):

i = 1
while i < 3:
    print(i)
    i += 1
else:
    print("i is no longer less than 3")

TL;DR

  • while condition: repeats while true.
  • Update the condition or you'll loop forever.
  • break exits; continue skips to the next check.
  • else runs when the loop ends naturally.