Helper variables: counting and summing
Variables that keep track of something while a loop runs are called helper variables. A typical one counts things, and another adds up a total:
items = 0
total = 0
while True:
price = int(input("Price (0 to finish): "))
if price == 0:
break
items += 1
total += price
print(f"{items} items, total {total} euros")
3
12
5
0Price (0 to finish): 3
Price (0 to finish): 12
Price (0 to finish): 5
Price (0 to finish): 0
3 items, total 20 eurosBoth helpers get their starting value, 0, before the loop, and each iteration updates them. The 0 that ends the loop isn't counted, because the break comes before the updates.
Start before the loop
Where the starting value is set matters. If it is set inside the loop, the helper starts over on every iteration:
while True:
count = 0
word = input("Word (stop to finish): ")
if word == "stop":
break
count += 1
print(f"You typed {count} words.")
sun
moon
stopWord (stop to finish): sun
Word (stop to finish): moon
Word (stop to finish): stop
You typed 0 words.On the last iteration, count = 0 runs once more just before the break, so the count is lost. Move that line above while True:, and the program says 2.
Remembering how the loop ended
A loop can have more than one break. A helper variable can remember which one ended it, so that the code after the loop knows what happened. This minibus has 3 seats. It leaves when every seat is taken, or earlier, when nobody else is waiting:
seats = 3
on_board = 0
while True:
name = input("Passenger (end when nobody is left): ")
if name == "end":
full = False
break
on_board += 1
print(f"Welcome aboard, {name}!")
if on_board == seats:
full = True
break
if full:
print("The bus is full. Next stop!")
else:
print(f"The bus leaves with {on_board} passengers.")
Ada
Ben
endPassenger (end when nobody is left): Ada
Welcome aboard, Ada!
Passenger (end when nobody is left): Ben
Welcome aboard, Ben!
Passenger (end when nobody is left): end
The bus leaves with 2 passengers.With a third name instead of end, the second break would end the loop, with full set to True. full holds True or False, so it can be the condition of an if all by itself.