Repeat a block for as long as a condition stays true.
# while condition is True
count = 0
while count < 5:
print(count)
count += 1
# ans: 0, 1, 2, 3, 4
The condition is checked before every pass, including the last one that fails.
# countdown
x = 3
while x > 0:
print(x)
x -= 1
# ans: 3, 2, 1
x =
# infinite loop with break
x = 0
while True:
x += 1
if x > 5:
break
# ans: x is 6
while True never stops by itself: break is the only way out.
# increment by different values
x = 0
while x < 10:
x += 2
# ans: x is 10 (after the last iteration)
Predict the result, then press → to trace the loop and check.
# what is count after?
count = 0
while count < 5:
count += 1
# ans: count is 5
# how many prints?
x = 3
while x > 0:
print(x)
x -= 1
# ans: 3 prints (3, 2, 1)
# what happens?
x = 0
while x < 5:
x += 2
# ans: x is 6 (after the last iteration)
# infinite loop?
x = 0
while x >= 0:
x += 1
if x > 5:
break
# ans: x is 6 (breaks when x becomes 6)
# what is x?
x = 10
while x > 0:
x -= 3
# ans: x is -2 (10, 7, 4, 1, -2)
# condition never true?
x = 0
while x > 0:
x += 1
# ans: the loop never runs, x is 0
# what prints?
x = 1
while x <= 4:
print(x)
x *= 2
# ans: 1, 2, 4
# tricky: what is x?
x = 0
while x < 3:
x += 1
else:
x += 10
# ans: x is 13 (3 + 10)
The else of a loop runs when the loop ends without break. See Loop Else.
# what is the final value?
x = 100
while x > 1:
x = x // 2
# ans: x is 1 (100, 50, 25, 12, 6, 3, 1)
Once x reaches 1, 1 > 1 is False, so it never gets halved to 0.
# condition check?
x = 5
while x:
x -= 1
# ans: x is 0 (5, 4, 3, 2, 1, 0)
The condition is tested before each pass; if it starts False the body never runs.
The body must move the condition towards False, or the loop runs for ever.
breakLeaves the loop at once, wherever it is in the body.
while x: keeps going while x is non-zero.