break – stop the loop now
break jumps out of the loop immediately, even if there are more rounds left:
for number in range(1, 100):
if number % 7 == 0:
print("First multiple of 7 is", number)
breakOutput
First multiple of 7 is 7
continue – skip this round
continue skips the rest of the current round and goes straight to the next one:
for number in range(1, 11):
if number % 3 == 0:
continue
print(number, end=" ")
print()Output
1 2 4 5 7 8 10
Numbers that divide by 3 were skipped. (end=" " makes print put a space instead of a new line.)
while True with break
A common pattern: loop forever, and break when you're done.
total = 0
while True:
entry = input("Number (or 'stop'): ")
if entry == "stop":
break
total += int(entry)
print("Total:", total)Output (when you type 10, 20, 5, then stop)
Number (or 'stop'): 10 Number (or 'stop'): 20 Number (or 'stop'): 5 Number (or 'stop'): stop Total: 35
Remember:
break= leave the loop.continue= skip to the next round.