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 1010 times. We can stop, once we find x.

That’s what the break keyword is for. It can break the loop whenever we want.

Press + to interact
Python 3.5
n = 10
x = 4
found = False # This bool will become true once x in found
for i in range(0, n):
if x == i+1:
found = True
print("Number found")
break
else:
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.

Press + to interact
Python 3.8
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.