continue Statement

The continue statement is one of Python’s control flow tools. It’s used to skip the rest of the code inside the enclosing loop for the current iteration and proceed to the next iteration.

Usage of continue Statement

The continue statement is used when we want to skip over the part of the loop where the control has been transferred, but we don’t want to terminate the loop. Basically, the continue statement ends the current iteration and proceeds to the next iteration of the loop.

It can be used in both for and while loops.

1for letter in 'Python': 
2   if letter == 'h':
3      continue
4   print ('Current Letter :', letter)

In the above example, when the letter ‘h’ is encountered, the continue statement ends the current iteration and the control goes to the next iteration, skipping the print statement for the letter ‘h’.

continue Statement in Nested Loops

The continue statement in Python only affects the enclosing loop, meaning the loop that it directly belongs to. In a nested loop structure, if the continue statement is encountered in the inner loop, it does not affect the outer loop’s iteration. It only skips the current iteration of the inner loop and continues with the next iteration of the inner loop.

See this example:

1for i in range(1, 6):
2    for j in range(1, 4):
3        if(j==2):
4            continue
5        print(j, end=' ')
6    print()

In this example, the continue statement only affects the inner for loop when j equals 2.

Note

‘in’ operator in ‘for’ loop in Python: When we say ‘for letter in ‘Python’’, it means, on each iteration, the ’letter’ variable is assigned the next character in the string ‘Python’.

Continue vs Break

Unlike break, continue does not terminate the execution of the loop entirely. break “breaks” the looping whereas continue just skips the current iteration and immediately continues onto the next. Remember, continue does not work with the try-catch construct.

‘‘‘python {linenos=true} for num in range(2, 10): if num % 2 == 0: print(“Found an even number”, num) continue print(“Found a number”, num) ’’’ In the above example, if the condition in the if statement is True, it outputs “Found an even number”, then continue skips the rest of the loop and continues with the next iteration. If the condition is False, it outputs “Found a number”.

Make sure to wisely use continue statement as using it without a correct condition could result in an infinite loop.