Computers are great at doing the same thing many times without getting bored. A loop repeats a block of code. The first kind is the while loop: it checks its condition, runs the block if the condition is True, then goes back and checks again, over and over until the condition is False.
Follow it step by step: count is 1, 1 <= 3 is True, so it prints Lap 1 and count becomes 2. Then 2, then 3. When count becomes 4, 4 <= 3 is False and the loop ends. Each trip through the block is called an iteration.
Something inside the loop has to change the condition eventually. If nothing does, the loop runs forever. This is called an infinite loop, and the program seems to freeze. (In most editors, Ctrl+C or a Stop button ends it.)
A counter is a variable that counts how many times something happened, and an accumulator is one that builds up a total. Both start before the loop and change inside it.
total = 0
n = 1
while n <= 4:
total += n
n += 1
print(total)
Prints
10
break leaves a loop straight away, wherever it is. It's often used with while True:, a loop that would run forever if nothing stopped it, when you only find out inside the loop that it's time to stop.
n = 1
while True:
if n * n > 50:
break
n += 1
print(n)
Prints
8
This finds the first number whose square is over 50. A typical real use is a menu: keep asking the user what to do until they type "quit", then break.
while True:
choice = input("Command (or quit): ")
if choice == "quit":
break
print("You typed", choice)
Practice
What does this print? (Separate the lines with spaces.)
n = 3
while n > 0:
print(n)
n -= 1
More info
Quick reference
while cond:
Repeats the indented block as long as cond is True.
iteration
One trip through a loop's block.
infinite loop
A loop whose condition never becomes False. Ctrl+C stops it.
break
Leave the loop now.
counter / accumulator
A variable that counts / adds up, set before the loop and changed inside it.