Python Continue Statement

Python also has a continue keyword for when you want to skip to the next loop iteration. Like in most other programming languages, the continue keyword allows you to stop executing the current loop iteration and move on to the next iteration.

As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.

The continue statement can be used in both while and for loops.

 Continue Statement with While Loop:

i = 1
while i <= 5 :
    if i == 2 or i==4 :
        i += 1
        continue
    print(i)
    i += 1

Output:

1
3
5

Continue Statement with For Loop and Range:

for letter in 'Hello':
    if letter == 'l':
        continue
    print('Current Letter :', letter)

Output:

Current Letter : H
Current Letter : e
Current Letter : l
Current Letter : o

We use continue statement to skip the execution of further statements during that iteration and continue with next iterations or elements in the collection.

Tags