The break
keyword helps to stop the iteration of looping statements.
numbers_list = [
0, 1, 2, 3, 4, 5
]
for number in numbers_list:
if number == 3:
break
print(number)
0
1
2
In the above example, we used a for loop to print the numbers 0
to 5
. However, if the number
equals 3
(number == 3
), then after we break
the for loop iteration since the number only prints from 0
to 2
, and then it stops.
The continue
keyword allows us to stop the current iteration of the loop and continue with the next.
numbers_list = [
0, 1, 2, 3, 4, 5
]
for number in numbers_list:
if number == 3:
continue
print(number)
0
1
2
4
5
In the above example, we used a for loop to print the numbers 0
to 5
. However, if the number
equals 3
(number == 3
), call the continue
keyword because calling the continue
will skip the current iteration and move to the next. In the output, you see the numbers 0
to 5
are displayed, but the number 3
is missing.