Skipping a round with continue
break leaves the whole loop. continue leaves only the current round: the rest of the body is skipped, and Python goes straight back to the top of the loop, checks the condition, and starts the next round if it's true.
This program adds up prices, but skips any price over 100, which it takes to be a typo:
total = 0
while True:
price = int(input("Price (0 to stop): "))
if price == 0:
break
if price > 100:
print("Skipped, too big")
continue
total += price
print(f"Total: {total}")
20
500
15
0Price (0 to stop): 20
Price (0 to stop): 500
Skipped, too big
Price (0 to stop): 15
Price (0 to stop): 0
Total: 35For the price 500, continue skips total += price, and the next round asks for a new price.
continue never does anything an if couldn't do: the same loop could put total += price in an else. But when a round can be skipped for several reasons, a check with continue for each one at the top of the body keeps the rest of the body simple, instead of nested deeper and deeper in ifs.
continue and the update
In a loop that counts, continue holds a trap. This loop prints the numbers from 1 to 10, except the multiples of 3:
number = 0
while number < 10:
number += 1
if number % 3 == 0:
continue
print(number)
1
2
4
5
7
8
10The update number += 1 comes first in the body, before the continue. Here is what happens with the update at the end, where it usually is:
number = 1
while number <= 10:
if number % 3 == 0:
continue
print(number)
number += 1
It prints 1 and 2. Then, with number at 3, continue jumps back to the top before the update. number stays 3, every round is skipped the same way, and the loop never ends. So with continue in a loop, make sure the update happens on every path through the body.