Python continue Statement
continue Statement
Python's continue
statement skips the current iteration of a loop and continues with the next iteration.
note
In contrast to the break
statement, the loop does not end, but continues with the next iteration.
Continue in for and while Loop
The continue
statement is used to skip the rest of the code inside a loop for the current iteration only.
The loop continues with the next iteration.
For example, continue the loop at yellow
:
For Loop
colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'yellow':
continue
print(x)
Output
red
green
blue
While Loop
colors = ['red', 'green', 'yellow', 'blue']
i = 0
while i < len(colors):
i = i + 1
if colors[i-1] == 'yellow':
continue
print(colors[i-1])
Output
red
green
blue
Continue inside try-finally Block
If you have a try-finally
block within a for
or while
statement, after the continue
statement is executed, the finally
clause is executed before starting the next iteration.
For example, a try…finally block in a for loop:
For Loop
for x in range(3):
try:
print('trying...')
continue
print('still trying...')
except:
print('Something went wrong.')
finally:
print('Done!')
print('The end.')
Output
trying...
Done!
trying...
Done!
trying...
Done!
The end.
For example, a try…finally block in a for loop:
While Loop
i = 0
while i<3:
try:
print('trying...')
i = i + 1
continue
print('still trying...')
except:
print('Something went wrong.')
finally:
print('Done!')
print('The end.')
Output
trying...
Done!
trying...
Done!
trying...
Done!
The end.