Using Python break and continue keywords


Gaming Laptop Series

The break and continue are keywords used in Python to alter the normal flow of loops. A loop iterate over a line or block of code repeatedly until the given condition becomes false.

Now, what if you want to continue or exit from the loop immediately after a certain condition meets, you can do this by using continue and break keywords.

In this article, we will discuss the usage of these keywords in Python along with some examples.

Python break keyword

When the Python interpreter encounters the break statement while executing a code it immediately gets out of the body of the loop. It starts executing the statement given after the body of the loop or block of code where the break statement is used.

Syntax :

You can simply use the break keyword as it is given below in your code.

break

For example:

You can see the example which is given below. It demonstrates the use of the break keyword in Python.

for i in range(1,11):
            if i == 5:
              break
            print(i)

You can see the output in the given image –

When the value of i becomes equal to 5, the break statement will be executed and the control flow will get out of the loop.

Python continue keyword

When the interpreter finds the continue statement it skips all the remaining statement(s) of the loop for the current iteration. In the next iteration, it continues the execution of the remaining statements.

Syntax:

The continue keyword can be used in Python as it is given below.

continue

For example:

for i in range(1,11):
                if i == 5:
                 continue
                print(i)

Now you can see the output of this code in the given image –

When the value of i becomes equal to 5, the continue statement will be executed the interpreter will skip the execution of all the remaining statements of that block for the current iteration and start the next iteration.

So here print statement will not be executed when the value of i is 5.

Conclusion

This is how you can use the break or continue keywords in Python code. Now if you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.