Python while True with break
A while True loop has a condition that is never false, so it repeats until a break inside it runs. Use it when the reason to stop is only known in the middle of the loop body.
Read While Loops and break and continue first. Every block below uses fixed data, and its output is described under it.
Loop until a test passes
counter = 0
while True:
counter = counter + 1
if counter * counter > 50:
break
print(counter)
8 * 8 is the first square over 50, so the loop stops with counter at 8. Without the break, this loop would never end.
The loop-and-a-half pattern
Often you must get a value before you can test it. With while True, you get it once, at the top, then decide.
replies = ["yes", "maybe", "", "no"]
position = 0
while True:
reply = replies[position]
position = position + 1
if reply == "":
break
print("Got", reply)
print("Stopped at the blank reply")
The blank reply is the sentinel: it means "no more data" and is not printed. Here replies stands in for input() calls, so the block runs the same every time. A real program would call input() on the line that reads reply.
Choosing while True over a condition
The same loop can be written with a normal condition, but then the value must be read twice: once before the loop and once at the end of the body.
replies = ["yes", "maybe", "", "no"]
position = 0
reply = replies[position]
while reply != "":
print("Got", reply)
position = position + 1
reply = replies[position]
print("Stopped at the blank reply")
Both print the same lines. Prefer while True when the read is more than one line, so it is written only once. Prefer a real condition when the stop test is simple and known before the body runs, because the reader sees it straight away.
Watch out: a missing break
If no path through the body reaches break, the loop runs forever and the program freezes. Here the stop value is misspelt, so it is never found:
replies = ["yes", "Quit"]
position = 0
while True:
reply = replies[position]
position = position + 1
if reply == "quit": # never matches "Quit"
break
This loop does not freeze: it runs off the end of the list and raises IndexError on the third pass. With real input() it would wait for ever. Check that every while True loop has a stop value the data can actually reach.
Note: these examples leave out reading real input and checking that it is valid. For checking input in a retry loop, see Retrying until the input is valid.
Your turn
Add up the scores until you reach the sentinel -1, using while True and break. Then print the total and how many scores were added.
scores = [7, 3, 9, -1, 5]
position = 0
total = 0
# add a while True loop: read scores[position], move position on,
# break at -1, otherwise add the score to total
print(total)
print(position - 1)
Expected output
19
3