Python – Continue Statement

In Python, the continue statement allows the programme to skip a block of code for the current loop iteration. The continue statement returns the programme to the beginning of the loop whenever the condition is met.

When the continue statement is used in a nested loop (loop inside the loop), it skips the code block of the innermost loop after the condition is met.

Continue statement with While loop

Python – Continue Statement: If the value of variable j becomes 4, the continue statement is used to bypass the while loop in the example below.

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

The output of the above code will be:

1
2
3
this iteration is skipped.
5
6

Continue statement with For loop

If the value of variable x becomes ‘yellow,’ the continue statement is used to bypass the for loop in the example below.

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

The output of the above code will be:

red
blue
green
this iteration is skipped.
black
white

Continue statement with Nested loop

When the condition is met, the continue statement skips the inner loop’s code block. For multiplier = 100, the programme skips the inner loop in the example below.

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

The output of the above code will be:

# nested loop without continue statement
10
100
1000
20
200
2000
30
300
3000
# nested loop with continue statement  
digits = [1, 2, 3] 
multipliers = [10, 100, 1000]
print("# nested loop with continue statement")
for digit in digits:
  for multiplier in multipliers:
    if (multiplier == 100):
      continue
    print (digit * multiplier)

The output of the above code will be:

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

Also Read: Java – Continue Statement

Leave a Reply

Your email address will not be published. Required fields are marked *