LambdaLabTM
Computer Science · Class 11 · Iterative Statements
IterationCount unknown⏱️ 12 min read

The while Loop

The loop for when nobody knows how many rounds it will take — not you, and not the program. Instead of a collection of values, it has a condition, and it keeps repeating for as long as that condition is True. Which means something inside the loop must eventually make it False, and that duty is yours.

1Where for cannot help

Ask the user for a password and keep asking until it is right. How many times? There is no answer to give a range() — it depends on who is typing, and it is settled only while the loop is already running.

password.py
# how many tries will it take? nobody knows — so: while
password = input('Password: ')

while password != 'lambda':
    print('Wrong. Try again.')
    password = input('Password: ')

print('Welcome!')
Output
Password: open
Wrong. Try again.
Password: sesame
Wrong. Try again.
Password: lambda
Welcome!

Three rounds this time. Next time it might be one, or nine. That is exactly the shape a while loop is for.

2How it is written

shape.py
while condition:
    statement
    statement
next statement

It is an if that comes back. The header looks identical — the same kind of condition, the same colon, the same indented block — and there is exactly one difference: when the block finishes, Python goes back and asks the condition again instead of moving on.

Condition is Trueifwhile
the block runsonceagain and again
after the blockcarry on belowask the condition again

3The three jobs a while loop needs

A for loop counts for you. A while loop counts for nobody, so when you are using one to repeat a set number of times, three things have to be written by hand — and they sit in three different places:

hello_while.py
# printing hello 5 times using a while loop
i = 1

while i <= 5:
    print('hello')
    i = i + 1
Output
hello
hello
hello
hello
hello
  1. Start the counteri = 1, above the loop, so it happens once.
  2. Test itwhile i <= 5:, checked before every round.
  3. Move iti = i + 1, inside the block, so the loop gets closer to ending.

Miss the first and you get a NameError. Miss the third and you get something far worse — nothing at all, for ever. Step through it below, then press delete i = i + 1 and step through the same loop again:

♾️ Watch the condition being re-asked

Step through it, then delete the update line and step through it again.

round 0
hello_while.py
headerbody — the indented blockoutside
i = 1
while i <= 5:
print('hello')
i = i + 1
print('Done')
in memory
i =1
the condition
1 <= 5True
output
nothing yet

Before the loop: i is set to 1. A while loop has no values of its own, so somebody has to start the counter — that is this line.

4The infinite loop

With the update line gone, i stays 1. The condition 1 <= 5 is True now, and it will still be True on the thousandth round, because nothing in the loop ever changes i. The program does not crash. It does not finish either. It just keeps printing hello until you stop it.

Key Takeaway
An infinite loop is a loop whose condition never becomes False. It is not a syntax error and Python will not warn you — the program is doing exactly what it was told. In IDLE you stop one with Ctrl + C.
Watch Out
Do not run one in the playground on this page. The Python here runs inside your browser tab, so a loop that never ends freezes the page rather than printing into a terminal you can interrupt. The stepper above is the safe way to watch one happen.

Not every endless loop is a mistake, though. while True: is a deliberate one, used when the program should keep going until something inside it decides to stop — a menu that runs until you choose Exit, for instance. Leaving it needs the break statement, which is the jump-statement lesson, so for now: every while loop you write needs a line that moves it towards the end.

5The loops only while can write

The hello-five-times example is a for loop in disguise — it is here to show the mechanics, not because it is a good use. This is a good use: the number of rounds depends on the values themselves.

balance.py
# spend 100 a week until the money runs out
balance = 500

while balance >= 100:
    balance = balance - 100
    print('Spent 100, balance is now', balance)

print('Not enough left to spend.')
Output
Spent 100, balance is now 400
Spent 100, balance is now 300
Spent 100, balance is now 200
Spent 100, balance is now 100
Spent 100, balance is now 0
Not enough left to spend.

Change the starting balance to 850 and the loop runs eight times instead of five, without a single edit to the loop. Nobody counted; the condition did.

Note
The condition is checked before the first round too. If it is False at the start — a balance of 50 here — the block never runs at all, not even once, and the program goes straight to the line below. A while loop can run zero times, exactly like a for loop over an empty range.

6The same program, both ways

Anything a for loop does, a while loop can do — it just makes you write the counting yourself:

for — the counting is done for you
for i in range(1, 6):
    print('hello')
while — you do the counting
i = 1

while i <= 5:
    print('hello')
    i = i + 1

Two lines against five, and three chances to make a mistake instead of none. That is the whole argument for using for whenever the count is known — and the reason while exists is the password loop, where no range() could have been written at all.

7Try it

Change the starting balance and watch the number of rounds change with it. Try 850, then 50 — the second one should print nothing but the last line.

balance.py

8Recap

Key Takeaway
while condition: repeats its block for as long as the condition is True, checking it before every round — including the first, so it may run zero times. Use it when the number of repetitions is not known beforehand. Something in the block must move the loop towards False, or it becomes an infinite loop: no error, no end.
Quick Check

What makes a while loop infinite?

Quick Check

balance = 50, and the loop is 'while balance >= 100:'. How many times does the block run?

Quick Check

Which task genuinely needs a while loop rather than a for loop?