Python

Python Continue Statement

The continue statement skips the current iteration of a loop and continues with the next iteration.

Continue in for and while Loop

Here’s how you can implement continue statement in a for and while loop.

Example: continue statement in a for loop

# skip 'blue'
colors = ['red', 'green', 'blue', 'yellow']
for x in colors:
    if x == 'blue':
        continue
    print(x)

Output:

red green yellow

Example: continue statement in a while loop

# skip odd numbers
x = 6
while x:
	x -= 1
	if x % 2 != 0:
		continue
	print(x)

Output:

4 2 0

Continue Inside try-finally Block

If you have try-finally block inside a for or while statement; after execution of a continue statement, the finally clause is executed before starting the next iteration.

Example: for Statement

for x in range(2):
  try:
      print('trying...')
      continue
      print('still trying...')
  except:
      print('Something went wrong.')
  finally:
      print('Done!')
print('Loop ended.')

Output:

trying...
Done!
trying...
Done!
Loop ended.

Example: while statement

x = 2
while x:
  try:
      print('trying...')
      x -= 1
      continue
      print('still trying...')
  except:
      print('Something went wrong.')
  finally:
      print('Done!')
print('Loop ended.')

Output:

trying...
Done!
trying...
Done!
Loop ended.