Python continue
is a keyword that will tell your code to move to the next item in a loop. It will skip all other code that comes after your continue
statement. This is heavily used with for
and while
loops in python.
for i in range(10): if i == 3: continue print (i)
Let’s talk about the example above. Imagine that you’re looping through the range(10) and you want to print each number except for 3. You can have a conditional statement to look for the number 3. If you find it, then tell python to continue on to the next item in your list.
Keep in mind that if you have nested loops, continue will only skip the item within the first loop it is placed in.
Let’s take a look at a python continue code sample
Python Continue¶
In python, continue will 1) skip the rest of your code in your loop and 2) move to the next item in your loop.
Let's look at a few examples. Regular loop and nested loops
Notice how the code below skips printing '3' because we have a conditional that checks for it then continues
for i in range(6):
if i == 3:
continue
print (i)
Notice below how the only loop that gets skipped is within the nested (the range() loop).
The letter loop still continues on with the item it is currently looping
for letter in ['a', 'b', 'c']:
for num in range(4):
if num == 2:
continue
print (letter, num)
Check out more Python Vocabulary on our Glossary Page