PLAY FREE ▸
Snekcade › Python guides › While loops
PYTHON FOR BEGINNERS · LOOP LAGOON

Python while loops explained

Repeat until something happens: lives run out, the answer is right, the goal is reached.

5 min read · updated November 2026

A while loop keeps repeating as long as a condition is true. Use it when you don't know in advance how many times something should happen: until the player runs out of lives, until the answer is right, until the money runs out.

THE BASIC SHAPE

lives = 3
while lives > 0:
    print("Still alive! Lives:", lives)
    lives -= 1
print("GAME OVER")
Still alive! Lives: 3
Still alive! Lives: 2
Still alive! Lives: 1
GAME OVER
Something inside the loop must change the condition. Here lives -= 1 does it. Without it, the loop would never end.

COUNTING UNTIL A TARGET

coins = 1
days = 0
while coins < 100:
    coins *= 2
    days += 1
print(days, "days,", coins, "coins")
7 days, 128 coins

This is the classic while question: how many steps until we reach the goal? A for loop can't answer it as easily, because you don't know the number of steps up front.

BREAK: LEAVE THE LOOP EARLY

while True loops forever, so it needs a break to stop. This pattern is common when the exit point is in the middle of the loop.

n = 0
while True:
    n += 7
    if n % 5 == 0:
        break
print(n)
35

CONTINUE: SKIP TO THE NEXT PASS

n = 0
while n < 6:
    n += 1
    if n % 2 == 0:
        continue
    print(n)
1
3
5

continue jumps straight back to the condition check, skipping the rest of the body for that pass.

WHILE OR FOR?

WHAT DOES THIS PRINT?
x = 10
while x > 3:
    x -= 3
print(x)
x goes 10 → 7 → 4 → 1. At 1 the condition x > 3 is false, so the loop stops and prints 1.

COMMON BEGINNER MISTAKES

The infinite loop. Forgetting to change the variable in the condition, so it stays true forever. If your program freezes, check this first.
Off by one. < and <= differ by one pass. Trace the last pass by hand to be sure.
Using while for a list. To go through every item, a for loop is shorter and safer.

PRACTICE IT, DON'T JUST READ IT

Loop Lagoon in Snekcade has you predict and fix loops with swipes, then write your own. It is one of the free worlds.

PLAY LOOP LAGOON ▸

FAQ

What is a while loop in Python?

A loop that repeats its body as long as a condition is true. Python checks the condition before every pass.

How do I stop an infinite while loop?

Make sure something inside the loop changes the condition, or use break. To stop a running program in a terminal, press Ctrl+C.

When should I use while instead of for?

Use while when you repeat until something happens and do not know the number of steps in advance. Use for to go through a list or a known count.