Break and Continue Statement In Python. Topic – 14

Break and Continue Statement In Python

Break Statement:

Break statement is used to exit the loop without executing all loops. When we use the break statement will loop immediately terminate and control is transferred outside the loop. Let’s see an example:

for i in range(1, 6):
    if i == 3:
        break
    print(i)

Output
1
2

Here, a loop is running from 1 to 5, but when the value of ‘i’ becomes 3, due to the break statement, the loop terminates, and control is transferred outside the loop.

Break Statement with while Loop:

We can also terminate the while loop using the break statement. For example

i = 0

while i < 5:
    if i == 3:
        break
    print(i)
    i += 1

The Output Of This Code Will Be:

Output
0
1
2

How Break Statement Works:

Continue Statement:

Continue statement used to skip the next iteration immediately. When continuing statement executes, loop control transfers to the next iteration.

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

The Output Of This Code Will Be:

1
2
4
5

Here, when the value of ‘i’ becomes 3, due to the continue statement, the loop skips that iteration and directly moves to the next iteration, preventing the printing of 3.

The use of both these statements helps you control the loop and modify the loop behavior based on specific conditions.

How Continue Statement Work:

If you don’t know about  “For & While Loops in Python” just click on read more.

I hope you understand Break and Continue Statement In Python. If you do not understand this topic just comment below with your email ID, and I will mail back to you.

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

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

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog