Python Loop Continue and Break

In this section, you will learn the break and continue statements in Python programming with the help of examples.

break and continue statements:

The break statement breaks out of the innermost enclosing for or while loop.

The continue statement skips the current iteration and continues with the next iteration of the for or while loop.

Python break statement:

When the break statement is used in a loop, it will terminate the loop and control will be transferred outside the body of the loop. If you use the break statement in nested loops, the inner loop will be terminated.

The following is the syntax of the break in Python:

break

The break statement is often executed on the basis of a condition (if condition). When the condition is true, break is executed and loop (for, while) is terminated.

Using break:

for i in "Python":
        if i == "h":
            break
        print(i)
print("Outside for loop")
P
y
t
Outside for loop

Here i traverses through a sequence that is "Python" and when i becomes equal to h, the control enters if and the break statement is executed and the loop is terminated. Before i is not h, if is not executed and the print statement is executed to print the letters of the sequence "Python".

Python continue statement:

continue statement skips the current iteration and the control is transferred to the starting of the loop. In this case, the loop will not be terminated but continue with the next iteration.

The following is the syntax of continue statement:

continue

Using continue statement:

for i in "Python":
        if i == "h":
            continue
        print(i)
print("Outside for loop")
P
y
t
o
n
Outside for loop

Here when i becomes equal to h, the iteration will be skipped and it will continue with the next iteration. In this way, you can see in the output that h is not printed and the letters before and after h are printed.

So in the break statement after h nothing was printed but this is not the case with continue statement.