Day17 - Break and Continue 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
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'




