Skip to main content

Command Palette

Search for a command to run...

Day19- Break and Continuous Statement

Updated
2 min read
Day19- Break and Continuous Statement
C
I am Data Science student, has a little bit knowledge on Web Development. I also love writing and editing as my hobby. Passionate to explore the world.

break statement

Break Statement:

The break statement enables a program to skip over a part of the code. A break statement terminates the very loop it lies within.

Example :

for i in range(12):
    if(i == 10): #print table of 5 till 10
        break
    print("5 X", i+1, "=", 5 * (i+1)) 

print("Out of the Loop")

Output:

5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Out of the Loop

Key Points:

Loops works as iteration by iteration:

  • If we want to exit loop at particular loop - we use 'break statement'

  • If we want to skip iteration (code of loop body) at particular iteration - we use 'continue statement'

Continuous Statement:

The continue statement skips the rest of the loop statements and causes the next iteration to occur.

Example 1 :

for i in range(12):
    if(i == 10): #print table of 5 till 10
        print("Skip the iteration")
        continue
    print("5 X", i, "=", 5 * (i))

Output:

5 X 0 = 0
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
Skip the iteration
5 X 11 = 55

Example 2 :

for i in [2,3,4,6,8,0]: 
    if (i%2!=0): #skips odd number
        continue
    print(i)

Output:

2
4
6
8
0