Break and Continue Statement in Python

In this tutorial, we will learn about the Break and Continue statement in Python. These are used in the Python language during looping that is while and for loop. Basically these two statements are used to control the flow of the loop. The Break and continue statement have their own work let’s see them one by one.

Break statement in Python

The work of break statement is that When we use Break statement in while and for loop it immediately exit the loop in Python. Let’s see an example with for loop:

for number in range(100):
    if number == 10:
        break
    print(number,end=' ')

Output:

0 1 2 3 4 5 6 7 8 9

In the above example the loop is break when the number is equal to 10.  Again see the same example with while loop :

num=0
while num<=100:
     if num==10:
       break
     print(num,end=' ')
     num+=1

Output:

0 1 2 3 4 5 6 7 8 9

Continue statement in Python

when we use continue statement with for and while loop it skips the reminder part of the loop and terminate or restart the loop. Let’s first see the example with for loop:

for num in range(20):
    if num ==10:
        continue
    print(num ,end=' ')

Output

0 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19

As we see the output the number 10 is missing because at this stage the loop terminated or restart. Now we see the example with while loop:

num=0
while num<=19:
    num+=1
    if num == 10:
        continue
    print(num, end=' ')

Output:

1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 20

Thanks for reading. For more information about the basic concepts in Python you can also refer to the following links:

random() module in Python

Lambda Function In Python

Leave a Reply

Your email address will not be published. Required fields are marked *