Skip to main content

Command Palette

Search for a command to run...

Day17 - Break and Continue Statement

Published
2 min read
Day17 - Break and Continue 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

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

Continue statement:

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

Example 01:

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 02:

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

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'

100DaysofPython

Part 18 of 35

This series is for beginners in which we explore python language along with how it is used in data science and do some exercises and some python related projects.

Up next

Day18- Functions in Python

Built-in functions and User-defined functions