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
- Python checks the condition
lives > 0before every pass. - If it is true, the indented body runs, then Python goes back to the top and checks again.
- When it becomes false, the loop ends and the code after it runs.
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?
- for: you have a collection or a known count (every item in a list, 10 times).
- while: you repeat until something happens (until lives are 0, until the guess is right).
x = 10
while x > 3:
x -= 3
print(x)x > 3 is false, so the loop stops and prints 1.COMMON BEGINNER MISTAKES
< and <= differ by one pass. Trace the last pass by hand to be sure.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.