In this lesson, we'll learn the use of 'break' and 'continue' keyword in loops.
We'll cover the following
When adding a loop, we always decide the terminating condition. Let’s say we need to print first n
numbers; so we can write our loop as:
for n in range(0, 10):
print(n)
The break
Keyword
What if, we need to exit a loop before it reaches the end?
Suppose we have first ten natural numbers in a box, and we have to find whether x
number exists in that box or not. If x
is less than 10, we don’t have to run loop times. We can stop, once we find x
.
That’s what the break
keyword is for. It can break the loop whenever we want.
n = 10x = 4found = False # This bool will become true once x in foundfor i in range(0, n):if x == i+1:found = Trueprint("Number found")breakelse:print("Number not found")
The continue
Keyword
What if, we don’t want to exit the loop, but skip all the code in the current iteration and move to the next one?
That’s what the continue
keyword is for. Let’s see if we can repair the following code and make it run successfully. Our AI Mentor can guide us as well.
for i in range(0, 10):if i%2 == 0:continue # Skipping even numbers
Here, the continue
keyword is used to skip even numbers and print odd numbers only.
The loop goes into the if
block only when i
is an even number. In that case, continue
is executed and the rest of the iteration, including the print()
statement is skipped.
Get hands-on with 1400+ tech skills courses.