AlphaCodingSkills

Python - Continue Statement


Advertisements

Previous Page Next Page

The continue statement in Python let the program skip a block of codes for current iteration in a loop. Whenever continue statement condition is fulfilled, it brings the program to the start of loop. If the continue statement is used in a nested loop (loop inside loop), it will skip innermost loop's code block, whenever condition is fulfilled.

Continue statement with While loop

i = 6
j = 0
while (j < i):
    j = j + 1
    if(j == 4):
        print('this iteration is skipped.')
        continue
    print(j)

Output

1
2
3
this iteration is skipped.
5
6

Continue statement with For loop

color = ['red', 'blue', 'green', 'yellow', 'black', 'white']
for x in color:
    if(x == 'yellow'):
        print('this iteration is skipped.')
        continue
    print(x)

Output

red
blue
green
this iteration is skipped.
black
white

Continue statement with Nested loop

In the below example, continue statement skip the inner loop's block of codes whenever condition (when multiplier is either 'hi' or 'hello') is fulfilled.

# nested loop without continue statement	
digits = [1, 2, 3] 
multipliers = [10, 'hi', 'hello', 1000]
for digit in digits:
    for multiplier in multipliers:
        print (digit * multiplier)

# nested loop with continue statement	
digits = [1, 2, 3] 
multipliers = [10, 'hi', 'hello', 1000]
for digit in digits:
    for multiplier in multipliers:
        if(multiplier in ['hi', 'hello']):
            continue
        print (digit * multiplier)

Output

# output of nested loop without continue statement
10
hi
hello
1000
20
hihi
hellohello
2000
30
hihihi
hellohellohello
3000

# output of nested loop with continue statement
10
1000
20
2000
30
3000





Previous Page Next Page