Loops that count
A loop doesn't have to read input. Often a variable changes a little on every iteration, and the loop stops when the variable reaches a limit:
number = 1
while True:
print(number)
number += 1
if number > 5:
break
print("Done!")
1
2
3
4
5
Done!Follow it through: number starts at 1. Each iteration prints it and adds one to it. After printing 5, number becomes 6, the condition number > 5 is true, and break ends the loop.
The variable can change in other ways too. Remember -= and *= from part 1: seconds -= 3 is short for seconds = seconds - 3, and n *= 2 doubles n. Here is a countdown in steps of 3:
seconds = 10
while True:
if seconds < 0:
break
print(seconds)
seconds -= 3
print("Liftoff!")
10
7
4
1
Liftoff!After 1 comes -2, which is below 0, so the loop stops before printing it.
Where the check goes
In the first loop the check comes after the print, in the second one before it. Where you put the if with the break decides which values get printed. Here the check comes right after the variable changes, but before the print:
number = 1
while True:
number += 1
if number > 5:
break
print(number)
2
3
4
5Now the first value printed is 2, because number grows before it's printed for the first time. When a loop prints one value too many or too few, follow the variable one iteration at a time, on paper or with a print, and you'll see where the check should go.
One more thing: the variable must change inside the loop. Leave out number += 1, and number > 5 never becomes true, so the loop never ends.