while loops
A for loop goes through a list of items you already have. A while loop is different: it keeps going as long as a condition is true, however many rounds that takes. Use it when you do not know in advance how many times to repeat.
1oil = 32while oil > 0:3 print("The lamp burns, oil left:", oil)4 oil -= 15print("The lamp goes out")
The lamp burns, oil left: 3 The lamp burns, oil left: 2 The lamp burns, oil left: 1 The lamp goes out
How a while loop works
Before every round, Python checks the condition after while. If it is true, the indented body runs, and Python goes back to the top to check again. As soon as the condition is false, the loop ends and the program goes on below it.
- Is
oil > 0? 3 > 0, yes: print,oilbecomes 2. - 2 > 0, yes: print,
oilbecomes 1. - 1 > 0, yes: print,
oilbecomes 0. - 0 > 0, no: the loop ends.
Tip: Press Step on the example above. You will see Python jump back to the while line after each round and oil count down.
What does this print?
1n = 12while n < 100:3 n = n * 24print(n)
n doubles: 2, 4, 8, 16, 32, 64. 64 is still below 100, so the loop runs once more and n becomes 128. Only then is the condition false. The check happens at the top, never in the middle of a round.
Until something happens
while fits questions like "how many trips until the warehouse has 20 ore?". You cannot easily write that as a range(), but you can say when to stop.
1stored = 02trips = 03while stored < 20:4 stored += 65 trips += 16 print("Trip", trips, "- stored:", stored)7print("Done after", trips, "trips")
Trip 1 - stored: 6 Trip 2 - stored: 12 Trip 3 - stored: 18 Trip 4 - stored: 24 Done after 4 trips
Infinite loops
If the condition never becomes false, the loop never ends. That is an infinite loop. The usual cause is forgetting to change the variable the condition depends on:
| Code | What goes wrong |
|---|---|
while count <= 3: with no count += 1 inside | count stays the same, so the condition stays true forever. |
while lamps > 0: with lamps += 1 inside | lamps moves the wrong way and never reaches 0. |
while True: with no break | True is always true. |
A program stuck in an infinite loop prints the same thing again and again, or just seems to hang. On this site the engine stops a program after a very large number of steps. On your own computer, press Ctrl+C in the terminal to stop it. When it happens, check what makes the condition false, and make sure the body really gets there.
while True and break
Sometimes the right moment to stop is in the middle of a round, not at the top. Then write while True:, a loop that would run forever, and leave it with break, the same break you met with for.
1n = 12while True:3 n = n * 34 if n > 50:5 break6 print(n)7print("Stopped at", n)
3 9 27 Stopped at 81
The break is the only way out here, so make sure some round really reaches it.
Skipping with continue
continue jumps straight back to the condition and starts the next round. Here every third number is skipped:
1n = 02while n < 7:3 n += 14 if n % 3 == 0:5 continue6 print(n)
1 2 4 5 7
Notice that n += 1 comes before the continue. If it came after, a skipped round would never change n, and the loop would be stuck on the same number forever.
Asking until the answer is valid
while True is the classic way to keep asking until the user types something usable. Here the user typed ten, then 0, then 4:
1while True:2 text = input("How many lamps? ")3 if not text.isdigit():4 print("Please type a number.")5 continue6 lamps = int(text)7 if lamps == 0:8 print("At least one, please.")9 continue10 break11print("Lighting", lamps, "lamps")
How many lamps? ten Please type a number. How many lamps? 0 At least one, please. How many lamps? 4 Lighting 4 lamps
Each bad answer gets a message and a continue, which asks again. Only a good answer reaches the break. isdigit() is true when the text is made only of digits, so int(text) cannot fail.
A guessing game
Put it together: keep asking for guesses, give a clue each time, and stop when the guess is right.
1secret = 72tries = 03while True:4 guess = int(input("Your guess: "))5 tries += 16 if guess < secret:7 print("Too low")8 elif guess > secret:9 print("Too high")10 else:11 print(f"Got it in {tries} tries!")12 break
Your guess: 4 Too low Your guess: 9 Too high Your guess: 7 Got it in 3 tries!
A real game would pick a different secret number each time with the random module, which comes in a later lesson. Here it is fixed, so the example always gives the same result. Change secret and the answers, and try it.
for or while?
| Use | When | Example |
|---|---|---|
for | You have the items, or know how many rounds | each house on a street; 10 times |
while | You stop when something happens | until the warehouse is full; until the input is valid |
Anything a for loop does, a while loop can do too, but you must manage the counter yourself. These two print the same thing:
1for i in range(3):2 print("for", i)3i = 04while i < 3:5 print("while", i)6 i += 1
for 0 for 1 for 2 while 0 while 1 while 2
When both work, prefer for: it is shorter and it cannot turn into an infinite loop by accident.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it. If a loop does not stop, look at what should make its condition false.
Doubling
✓Start at 1 and keep doubling n while it is less than 1000. Count the doublings in steps.
10 doublings: 1024
1n = 12steps = 03# Your loop here4print(f"{steps} doublings: {n}")
The last lamp
✓This loop should light lamps 1 to 5, but it stops one lamp short. Fix it.
Lamp 1 Lamp 2 Lamp 3 Lamp 4 Lamp 5
1count = 12while count < 5:3 print("Lamp", count)4 count += 1
Add the digits
✓Add up the digits of n with a while loop: for 2024 that is 2 + 0 + 2 + 4.
8
1n = 20242total = 03# Your loop here4print(total)
What you learned
while condition:repeats its body as long as the condition is true; the check happens before each round.- Use
whilewhen you stop because something happens, not after a known number of rounds. - If the condition never becomes false, you have an infinite loop: make sure the body changes what the condition tests.
while True:withbreakstops in the middle of a round;continuestarts the next round.- Together they make it easy to ask until the input is valid, or to play a guessing game.