while loops: keep going until something changes
A while loop keeps repeating as long as something is true. It's perfect when you don't know how many times you'll go — like asking a player until they give a real answer.
The big idea
A while loop repeats its steps over and over while a test is true, and stops as soon as the test is false.
See it in code
The simplest while loop just repeats while a test is true. Here steps < 3 stays true until we've taken three steps down the hallway — the loop counts them for us:
steps = 0
while steps < 3:
print("You take a step...")
steps = steps + 1
print("You reach the door.")You take a step... You take a step... You take a step... You reach the door.
Each pass adds 1 to steps. Once steps reaches 3, the test steps < 3 turns false and the loop stops.
A while loop doesn't have to count — it can just watch a value. This one keeps going while your health isn't full, and each potion nudges that value closer:
health = 4
while health < 10:
print("You drink a potion. Health:", health)
health = health + 3
print("Full health! Health:", health)You drink a potion. Health: 4 You drink a potion. Health: 7 Full health! Health: 10
The loop can't know ahead of time how many potions it will take — it just keeps going while health < 10. That not-knowing-the-count is exactly what while is for.
Same shape, real job. In our text adventure the player must pick a direction — if they type nothing, we ask again. The pretend answers stand in for what they type; the loop keeps going while the choice is blank, and stops once a real answer arrives:
answers = ["", " ", "north"]
i = 0
choice = answers[i]
while choice.strip() == "":
print("Please type a direction.")
i = i + 1
choice = answers[i]
print("You go:", choice)Please type a direction. Please type a direction. You go: north
Just like the potions, we don't know the count ahead of time. The first two answers were blank, so the loop ran twice; the third was "north", so the test became false and the loop stopped. In a real program, input() would supply each answer as the player types it.
Use a while loop whenever you don't know the count ahead of time. Keep rolling until you get a six. Keep asking until the password is right. Keep bouncing the ball until it stops. The loop runs while the condition holds.
Try it yourself
Add another blank answer to the start of the list and watch the loop ask a third time. Then change the last answer to see the loop stop at a different point.
The common mistake
Forgetting to change the thing the test checks. If the choice never updates inside the loop, the test stays true forever and the program freezes — that's an infinite loop. Something in the loop must move it toward stopping.
What it unlocks
While loops build on conditionals, and let you keep reading answers with input() until they're valid.