How a while loop works
Python checks the condition. If it is TRUE, the body runs and Python goes back to check again. When it becomes FALSE, the loop ends.
n = 3
while n > 0:
print(n)
n = n - 1
print("Go!")Output: 3, 2, 1, then Go!.
for vs while
Use for when you know how many items to go through. Use while when you repeat until something happens, like a correct password or a counter reaching zero.
Stopping early with break
while True:
word = input("Type quit: ")
if word == "quit":
breakCommon beginner mistakes
- Forgetting to change the variable, creating an infinite loop.
- Writing the condition the wrong way round (
n < 0instead ofn > 0).
Practice exercises
Try each one yourself first, then open it in the Visualizer to watch every line run.
Exercise 1
Countdown
Count down from 5 to 1, then print "Lift off!".
n = 5
# while loop hereHint
Print n, then reduce it by 1 inside the loop.
Show solution and explanation
n = 5
while n > 0:
print(n)
n = n - 1
print("Lift off!")The condition is checked before every round. When n reaches 0, n > 0 is False and the loop ends. Without n = n - 1 it would never stop.
Watch the solution step by stepExercise 2
Sum until a limit
Add 1 + 2 + 3 + … and stop as soon as the total is more than 20. Print how many numbers you added.
total = 0
count = 0
# keep adding while total <= 20Hint
Increase count first, then add count to total.
Show solution and explanation
total = 0
count = 0
while total <= 20:
count = count + 1
total = total + count
print(count, total) # 6 21Watch both variables in memory: after 6 rounds total is 21, the condition 21 <= 20 is False, and the loop ends.
Watch the solution step by stepExercise 3
Find the first multiple
Find the first number from 1 upward that is divisible by both 4 and 6, using break.
n = 1
while True:
# stop when n fits both
n = n + 1
print(n)Hint
Use if n % 4 == 0 and n % 6 == 0: break — before increasing n.
Show solution and explanation
n = 1
while True:
if n % 4 == 0 and n % 6 == 0:
break
n = n + 1
print(n) # 12while True repeats forever, so break is the only exit. At n = 12 both remainders are 0 and break jumps straight to print.
Watch the solution step by step