Python break and continue with examples

Python break and continue with examples

In this tutorial, on how to create a python the break and continue statements are used to alter the flow of a loop.

The break and continue statement is used for optimizing the code and making it more readable by breaking out of a loop anytime.

 

Read also:

Python Flask tutorial Setting up a Flask and SQL Database Connection  

How to create a python flask with mysql database 

 

Python 'break' statement

The 'break' statement is used to exit a loop prematurely. 

Python break syntax:

 



break


When a break statement is encountered within a loop, the loop is immediately terminated and the program control paused or resumes at the next statement following the loop.

For Example:



for i in range(10):
    if i == 6:
        break
    print(i)


output:



0
1
2
3
4
5

In the above code, the loop will iterate over the range 0 to 9.

For Example:



if i == 5:
  break

When the value of the 'if' statement increased becomes '6', the 'break' statement is encountered and the loop is terminated. 

And the loop will print up to 5 and then the iterate will terminate.

Python continue statement


we can use the 'continue' statement is skip the remainder of the current iteration of a loop and move on to the next iteration. when a 'continue' statement is encountered within a loop.

The 'continue' is control jumps back to the beginning of the loop and the loop continues executing.

For Example:



for i in range(10):
    if i % 3 == 0:
        continue
    print(i)

Output:



1
2
4
5
7
8

In the above 'continue' code is loop will iterate over the range of 0 to 9. when the value is even the continue statement is encountered the program control jumps back to the beginning of the loop. And the print statement is skipping and moving to the next iteration.

Python Using 'break' and 'continue' Together


When we are using this both the 'break' and 'continue' statements are together in a loop. And when both statements together carefully handled, In the order in which they appear can affect the behavior of the loop.

For Example:



for i in range(15):
    if i == 10:
        break
    if i % 3 == 0:
        continue
    print(i)

Output:



1
2
4
5
7
8

I hope you will learn how to create a python break and continue loop and understanding the statement.

Previous Post Next Post