A while loop repeats for as long as a condition stays true. That is exactly the tool that you want when the number of repetitions is not known in advance, and it is exactly the tool that hangs your program when you get it wrong. The difference between those two outcomes is not in the syntax, which is very simple, but in the discipline of making sure that the loop always has a way to finish.
The previous lesson in this module covered "for Loops and range(): Iterating with Intention", and the next lesson in this module is about "Nested Loops and the Curious loop-else".
When is a while loop the right choice?
Reach for while when the thing that you are looping over does not exist yet. Retrying a network call that sometimes fails, reading lines until you meet a sentinel, waiting for a condition to become true, or counting down to zero. In each of those cases the number of rounds is decided by the data and not by you.
count = 0
while count < 3:
print('tick', count)
count += 1
print('done, count is', count)
# The classic mistake: a condition that can never become false.
# Leave this commented out or your program runs forever.
# while count > 0:
# print('this line never stops')
That commented block is the failure mode that is worth understanding properly. A while loop makes no promise about how many times it runs, so the responsibility falls entirely on you to make sure that something inside the body eventually changes the condition. Every while loop that you write should have three parts in your head. There is the condition, there is the thing inside the loop that changes it, and there is the guarantee that the change really happens.
As a rule of thumb, if you can write the loop as "for each item in this collection", then use for. The while version asks you to manage an index, a comparison, and an increment, and every one of those is another chance to be off by one.
How do you break out of a loop safely?
Three keywords control the body of a loop. break leaves the loop immediately. continue skips the rest of the current round and starts the next one. pass does nothing at all, and it exists so that you can write a placeholder body without inventing a filler statement.
for number in range(1, 11):
if number == 6:
print('skipping 6')
continue
if number == 9:
print('stopping before 9')
break
print('processing', number)
print('the loop finished')
The while True pattern is the standard way to write a loop whose exit condition is checked inside the body instead of in the header. It is honest about what is happening, because it says that you keep going until something inside the loop says stop.
outcomes = ['timeout', 'timeout', 'ok']
MAX_ATTEMPTS = 5
attempt = 0
while True:
if attempt >= len(outcomes):
print('no more attempts available')
break
attempt += 1
outcome = outcomes[attempt - 1]
print('attempt', attempt, ':', outcome)
if outcome == 'ok':
print('succeeded on attempt', attempt)
break
Notice the guard at the top of the loop. A retry loop that can fail forever is a denial-of-service bug that you write against yourself, so cap the number of attempts and make the failure path explicit. The same pattern applies to a loop that waits for input. Give it a maximum number of tries, and decide clearly what happens when they run out.
How do you build an input loop that terminates?
Interactive loops need three things. They need a way to leave, they need a way to reject bad input, and they need a guarantee that the user cannot trap themselves inside it. The usual design is a sentinel value that ends the loop, together with validation that asks again instead of crashing.
answers = ['42', 'not-a-number', '7', 'quit']
index = 0
while index < len(answers):
raw = answers[index]
index += 1
if raw == 'quit':
print('leaving the loop')
break
try:
value = int(raw)
except ValueError:
print(repr(raw), 'is not a number, asking again')
continue
print('accepted', value)
The list here stands in for the keyboard, so the script runs to the end without waiting for anybody. In a real program the same loop reads input() instead, and you would also catch EOFError so that a closed input stream ends the loop instead of raising an exception.
There is one more failure mode to design for, and it is the case where a user types nothing at all. If the input can be empty, check for that explicitly before you convert it. int('') raises ValueError in exactly the same way that int('abc') does, and an empty line is a far more common accident than a typo.
There is a neater way to say "read until a sentinel" when the items come from a function rather than from a prompt. iter(callable, sentinel) calls the function again and again, and it stops as soon as the function produces the sentinel value.
def make_reader(items):
"""Return a function that hands back the next item each time it is called."""
remaining = list(items)
def reader():
return remaining.pop(0)
return reader
reader = make_reader(['first', 'second', 'STOP', 'third'])
for line in iter(reader, 'STOP'):
print('processed', line)
print('the loop ended at the sentinel')
The word STOP is never handed to the body of the loop, so the loop only ever sees the values that it should act on. The same idea has a shorter form when you already have a list. iter(['first', 'second', 'STOP'], 'STOP') walks the list and stops at the marker. You will meet this pattern constantly in parsers that read until a blank line or until a marker appears.
What is the else clause on a while loop?
Python allows an else block on both for and while loops. It runs when the loop ends normally, which means that the condition became false or the iterable was used up. It does not run when you leave the loop with break.
attempts = [5, 3, 8]
for attempt in attempts:
if attempt > 7:
print('too big, stopping early')
break
print('trying', attempt)
else:
print('every attempt was within the limit')
print('---')
for attempt in [5, 3, 8]:
if attempt > 7:
print('too big, stopping early')
break
print('trying', attempt)
Both loops look almost identical, and only one of them prints the "within the limit" message. In the first loop, no attempt exceeded the limit, so the loop simply ran out of items and the else block fired. In the second loop, the break skipped it. That makes this construct a compact way to say "the loop finished without finding anything wrong", which is exactly the shape of a search loop. The next lesson covers that construct in full.
Your turn: build a guessing game with a safety net
- Write a guessing game where the secret number is 7. Use a
while Trueloop, read the guess withinput(), and print whether the guess is too low, too high, or correct. - Add a maximum of five attempts. When they run out, print a message that names the number of attempts that were used, and leave the loop cleanly.
- Handle a guess that is not a number. Catch
ValueError, print a friendly message, and do not count that attempt against the player. - Add a sentinel so that the player can type
quitand stop at any point, and make sure that the quit path and the attempts-exhausted path print different messages. - Finally, rewrite the loop so that it uses
forover a list of possible guesses instead ofwhile, and confirm that the two versions behave in the same way for the same input sequence.
Loop patterns worth knowing
- Use
whileonly when the number of rounds comes from the data, and useforfor everything else. - Every
whileloop needs a condition, something that changes it, and a guarantee that the change happens. breakleaves the loop,continueskips to the next round, andpassis a deliberate no-op.- Cap retry loops with a maximum attempt count and an explicit failure path.
- The
elseclause on a loop runs only when the loop finished without abreak, which makes it a compact "nothing went wrong" signal. iter(callable, sentinel)is the tidy way to consume a stream up to a marker value.