Free visual Python lesson

Python while Loop — Explained Visually

A while loop repeats code as long as a condition stays true. Press Play and watch the check happen before every round.

Python code

1n = 3
2while n > 0:
3 print(n)
4 n = n - 1
5print("Go!")

Variables / Memory

Memory is empty.

Execution

STEP 1 / 13Step 1 of 13. Program starts.

Program starts.

Output

Flow chart

RanNowTrueFalseChecked, not taken◇ decision · ▱ input/output
StartStartn = 3n = 3n > 0?n > 0?print(n)print(n)n = n - 1n = n - 1print("Go!")print("Go!")EndEndTRUEFALSE

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":
        break

Common beginner mistakes

  • Forgetting to change the variable, creating an infinite loop.
  • Writing the condition the wrong way round (n < 0 instead of n > 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 here
Hint

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 step

Exercise 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 <= 20
Hint

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 21

Watch 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 step

Exercise 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)  # 12

while 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

Try your own code

Paste any code into the free visualizer, or sign up free for all visual lessons with quizzes and progress tracking.