Break and Continue
You have now learned about the two fundamental ways of repeatedly executing a block of code.
for
loopswhile
loops
- A
for
loop will repeatedly execute a block of code based on the length of the iterable. - A
while
loop will repeatedly execute a block of code until its condition stops being met.
In the case of a for
loop, what if you wanted to break the loop before it iterated through the entire length of the iterable? Also, what if you wanted to skip over a specific iteration? That is where the break
and continue
keywords come into play!
In this article, you're going to use the break
and continue
keywords to modify the behaviour of a for
loop.
Continue
The continue
keyword jumps over one iteration of the loop based on a condition.
You will iterate through a list of numbers that range from 0-9
numbers = list(range(0,10)) print(numbers)
>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If you want to print only even numbers to the console, you can use the continue
keyword to skip over an iteration where the number is odd.
for number in numbers: if number % 2 != 0: continue print(number)
>>0
>>2
>>4
>>6
>>8
When you place a modulo %
in between two numbers, it calculates the remainder of the first number divided by the second number. If the remainder is not equal to zero (!=)
means not equal, then the number is odd. In which case, the iteration must be skipped using the continue
keyword . This results in only even numbers being printed.
Break
What if you replaced the continue
keyword with break
?
for number in numbers: if number % 2 != 0: break print(number)
>>0
The break
keyword, unlike continue
, completely breaks out of the loop when executed.
This is all you need to know for loops! In the past two sections, you learned how to control the execution of your code through if-elif-else
statements and loops. Now that you know all about control flow with Python, the next section is entirely focused on organizing your code into functions.
See you there!