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.
# 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!')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
while condition:
statement
statement
next statementIt 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 True | if | while |
|---|---|---|
| the block runs | once | again and again |
| after the block | carry on below | ask 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:
# printing hello 5 times using a while loop
i = 1
while i <= 5:
print('hello')
i = i + 1hello hello hello hello hello
- Start the counter —
i = 1, above the loop, so it happens once. - Test it —
while i <= 5:, checked before every round. - Move it —
i = 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:
Step through it, then delete the update line and step through it again.
i =11 <= 5Truenothing yetBefore 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.
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.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.
# 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.')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.
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 i in range(1, 6):
print('hello')i = 1
while i <= 5:
print('hello')
i = i + 1Two 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.
8Recap
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.What makes a while loop infinite?
balance = 50, and the loop is 'while balance >= 100:'. How many times does the block run?
Which task genuinely needs a while loop rather than a for loop?