Like the break statement , the continue statement can only appear in the body of a loop. When the compiler encounters a continue statement, then the rest of the statements in the loop are skipped and the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing loop. Its syntax is quite simple, just type keyword continue as shown below.
Again like the break statement, the continue statement cannot be used without an enclosing for or a while loop. When the continue statement is encountered in the while and for loop, the control is transferred to the code that tests the controlling expression. However, if placed with a for loop, the continue statement causes a branch to the code that updates the loop variable.
Let’s write a program to demonstrate the continue statement.
for i in range(1, 11): if (i == 5): continue print(i, end=" ") print("\n Done")
#output 1 2 3 4 6 7 8 9 10 Done
Note that the code is meant to print numbers from 0 to 10. But as soon as i becomes equal to 5, the continue statement is encountered, so rest of the statements in the for loop are skipped. In the output, there is no 5. 5 is missing and could not be printed as continue caused early increment of i and skipping of statement that printed the value if i on screen.
The following syntax illustrate the use of continue statement in loops.
while (...): ... if condition: continue ... ... Transfers control to the condition expression of the while loop
for (...): ... if condition: continue ... ... Transfers control to the condition expression of the for loop
for (...): ... for (...): ... if condition: continue ... ... Transfers control to the condition expression of the inner for loop
Hence we conclude that the continue statement is somewhat the opposite of the break statement . It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. The continue statement is used to stop the current iteration of the loop and continues with the next one.