Watch on Instagram

Code Bytes · "Intro to Programming" · Episode 10 · Decisions and loops

While loops

A while loop keeps repeating as long as its condition is True and checks that condition before every round. count = 3 with while count > 0 prints 3, 2, 1 and then stops, because count - 1 eventually makes the condition False.

Posted · About a 1 minute watch, 4 minute read · Take the quiz

Keep going until something changes

A for loop is great when you know how many times to repeat something. But sometimes you don't know. You just want to keep going until something changes.

Think about stirring soup while it's lumpy. You check: still lumpy? Stir. Check again: still lumpy? Stir. Check again: smooth! Stop. You never decided "stir 12 times". You kept going while the soup was lumpy.

That is exactly what a while loop does.

A countdown

``python count = 3 while count > 0: print(count) count = count - 1 print("Liftoff!") ``

`` 3 2 1 Liftoff! ``

Read it piece by piece:

  • count = 3 makes a variable called count and stores 3 in it.
  • while count > 0: is the loop. Before every round, Python asks the question count > 0. If the answer is True, it runs the indented lines. Don't forget the colon.
  • The two indented lines are the inside of the loop: print(count) shows the current number, and count = count - 1 takes one away.

Round by round

| Round | count before | count > 0? | prints | count after | |---|---|---|---|---| | 1 | 3 | True | 3 | 2 | | 2 | 2 | True | 2 | 1 | | 3 | 1 | True | 1 | 0 | | check | 0 | False | (loop stops) | |

When count reaches 0, Python asks "is 0 greater than 0?" The answer is False, so the loop stops and Python moves on to the next line that isn't indented: print("Liftoff!").

for or while?

A simple rule of thumb:

  • Use for when you know how many times (run three laps, go through every letter).
  • Use while when you're waiting for something to change (keep asking until the password is right, keep stirring until it's smooth).

Often you can write the same thing either way; pick the one that reads more naturally.

Careful: something has to change

Look at what happens if you forget the minus-one line:

``python count = 3 while count > 0: print(count) ``

Now count is always 3, so count > 0 is always True, and the loop prints 3 again and again and never stops. That is called an infinite loop, and it's the topic of the next episode. (If you ever start one by accident, stop the program, for example with Ctrl+C in a terminal, or the Stop button in an online editor.)

Try it yourself

Open any free online Python editor (search "online Python") and run:

``python x = 10 while x > 0: print(x) x = x - 3 print("Done") ``

You should see:

`` 10 7 4 1 Done ``

Why does it stop after 1? Work it out: 1 - 3 is -2, and -2 > 0 is False. Now change x - 3 to x - 4 and predict the output before you run it.

Good to know

  • Every snippet on this page was run with Python 3 and printed exactly what is shown.
  • If the condition is False the very first time, the inside of the loop never runs at all. With count = 0, while count > 0: skips straight past the loop.
  • count = count - 1 can also be written count -= 1. Both do the same thing.
  • The condition can be any comparison from the last few episodes: <, >, ==, !=, and even and / or.
  • Next episode: infinite loops, the bug that never ends, and how to stop it.

Answer to the comment question

What does this print?

``python n = 1 while n < 20: n = n * 2 print(n) ``

It prints 32. n starts at 1 and doubles every round while n < 20 is True: 1, 2, 4, 8, 16. At 16, 16 < 20 is still True, so it doubles once more to 32. Now 32 < 20 is False, the loop stops, and print(n) (not indented, so it runs once after the loop) prints 32. The trap: the check happens before each round, not after, so the loop can go past 20.

Test your knowledge

Quick quiz: While loops

4 multiple-choice questions. Pick one answer for each, then check how you did.

1When does Python check the condition of a while loop?
2What does this print? count = 3 / while count > 0: / print(count) / count = count - 1
3When is a while loop the better choice than a for loop?
4What happens if you remove the line count = count - 1?

Sources

Video transcript

How do you make code keep going until something changes?

Use a while loop. It's like stirring soup while it's lumpy. Check, stir, check again, stop when it's smooth.

In Python: count equals three. Then while count is greater than zero, colon. Python asks that before every round.

Inside, indented: print count, then count equals count minus one. It prints three, takes one away, and checks again.

Three, two, one. Now count is zero. Zero greater than zero? False. The loop stops, and Python prints Liftoff!

Use for when you know how many times. Use while when you're waiting for something to change.

Careful: forget the minus one line, and count never changes. The loop never stops.

What does this print? Comment your answer below!

That's your byte.

More from "Intro to Programming"

All "Intro to Programming" lessons