Kodewick
Lesson 14 of 31Contents

while loops

Lesson 14 of 31 · Part 2 · Collections and loops · about 20 minutes

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.

main.py
1oil = 32while oil > 0:3    print("The lamp burns, oil left:", oil)4    oil -= 15print("The lamp goes out")
Output
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.

  1. Is oil > 0? 3 > 0, yes: print, oil becomes 2.
  2. 2 > 0, yes: print, oil becomes 1.
  3. 1 > 0, yes: print, oil becomes 0.
  4. 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.

Guess first

What does this print?

1n = 12while n < 100:3    n = n * 24print(n)

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.

main.py
1stored = 02trips = 03while stored < 20:4    stored += 65    trips += 16    print("Trip", trips, "- stored:", stored)7print("Done after", trips, "trips")
Output
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:

CodeWhat goes wrong
while count <= 3: with no count += 1 insidecount stays the same, so the condition stays true forever.
while lamps > 0: with lamps += 1 insidelamps moves the wrong way and never reaches 0.
while True: with no breakTrue 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.

main.py
1n = 12while True:3    n = n * 34    if n > 50:5        break6    print(n)7print("Stopped at", n)
Output
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:

main.py
1n = 02while n < 7:3    n += 14    if n % 3 == 0:5        continue6    print(n)
Output
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:

main.py
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")
Output
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.

main.py
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
Output
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?

UseWhenExample
forYou have the items, or know how many roundseach house on a street; 10 times
whileYou stop when something happensuntil 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:

main.py
1for i in range(3):2    print("for", i)3i = 04while i < 3:5    print("while", i)6    i += 1
Output
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.

Exercise 1

Doubling

Start at 1 and keep doubling n while it is less than 1000. Count the doublings in steps.

It should print
10 doublings: 1024
exercise1.py
1n = 12steps = 03# Your loop here4print(f"{steps} doublings: {n}")
Output
Press Run or Ctrl+Enter
Exercise 2

The last lamp

This loop should light lamps 1 to 5, but it stops one lamp short. Fix it.

It should print
Lamp 1
Lamp 2
Lamp 3
Lamp 4
Lamp 5
exercise2.py
1count = 12while count < 5:3    print("Lamp", count)4    count += 1
Output
Press Run or Ctrl+Enter
Exercise 3

Add the digits

Add up the digits of n with a while loop: for 2024 that is 2 + 0 + 2 + 4.

It should print
8
exercise3.py
1n = 20242total = 03# Your loop here4print(total)
Output
Press Run or Ctrl+Enter

What you learned

  • while condition: repeats its body as long as the condition is true; the check happens before each round.
  • Use while when 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: with break stops in the middle of a round; continue starts the next round.
  • Together they make it easy to ask until the input is valid, or to play a guessing game.