3.4 break and continue
break and continue both change the normal flow of a loop, but they mean different things.
break: end the current loop immediately.continue: skip the rest of the current iteration and start the next one.
break
Use break when the loop has already achieved its goal, or when continuing the loop no longer makes sense.
The program below checks whether an integer is prime. As soon as it finds one divisor of n, it knows n is not prime, so it can stop checking.
import math
n = int(input("Enter an integer: "))
is_prime = n > 1
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
is_prime = False
break
if is_prime:
print(n, "is a prime number")
else:
print(n, "is not a prime number")One possible run:
Enter an integer: 17
17 is a prime numberThere is no need to check all the way to n - 1. If a number has a factor larger than its square root, it must also have a paired factor smaller than its square root, so checking through sqrt(n) is enough.
continue
continue does not end the whole loop. It skips the remaining code in the current iteration and moves directly to the next iteration.
The program below reads 10 integers and computes the sum of squares of non-negative integers. When it sees a negative number, it skips that iteration.
n = 10
print("Enter %d integers:" % n)
sum_square = 0
for i in range(n):
num = int(input())
if num < 0:
continue
sum_square += num * num
print("Sum of squares of non-negative integers:", sum_square)One possible run:
Enter 10 integers:
5
7
-2
0
4
-4
-9
3
9
5
Sum of squares of non-negative integers: 205When num < 0, continue skips sum_square += num * num, so negative numbers do not contribute to the result. Note that 0 is not negative; its square is 0, so adding it does not change the total.
Choosing between them
Use break when you want the whole loop to stop. Use continue when you only want to skip the rest of the current iteration and let the next iteration begin normally.
for x in range(1, 6):
if x == 3:
continue
print(x)Output:
1
2
4
5The value 3 is skipped, but the loop does not end.
Comparison experiment
After reading what break and continue mean, use the component below to compare them step by step. When the loop reaches x == 3, continue only skips the current iteration, while break ends the whole loop early.