Break and Continue in Python

In Python, Break and Continue are statements executed inside a loop. These statements either skip according to the conditions inside loops or terminate loops at a point. If you want to learn all about the Break and Continue expressions in Python, this article is for you. In this article, I will walk you through a tutorial on Break and Continue in Python loops.

Break and Continue in Python

Break Statement

A break statement is used inside both the for and while loops. Whenever we execute a break statement inside a loop, the control flow terminates the loop immediately. For example, have a look at the code and its output below:

for i in range(0, 5):
    print(i)
    if i == 3:
        break
0
1
2
3

In the above for loop, we want to print the values between 0 to 5, but as we have given a condition that when the variable i gets equal to 3, the loop will terminate. So the loop terminated when i equalled 3.

Continue Statement

The continue statement, on the other hand, skips to the next iteration of the loop. It does not terminate the loop, like the break statement, when a given condition is satisfied. It skips to the next iteration. For example, have a look at the code and its output below:

for i in range(0, 5):
    if i == 3:
        continue
    print(i)
0
1
2
4

In the above for loop, we want to print the values between 0 to 5, but as we have given a condition here that whenever i equals 3, the continue statement will skip it and continue to the next iteration. That is why we cannot see 3 in the above output.

Summary

Whenever we execute a break statement inside a loop, the control flow terminates the loop immediately. The continue statement does not terminate the loop like the break statement when a given condition is satisfied. It skips to the next iteration. I hope you now have understood the break and continue statements in Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1433

Leave a Reply