Member-only story
Hi everyone, welcome back. Today, we will be going over the continue statement in Python and see how it works. The continue statement is used to stop a current iteration of a loop and continue onto the next iteration. This can be done in either a for loop or a while loop. With this introduction out of the way, let’s get into it.
Example: For Loop
Let’s see an example of us using the continue statement in a for loop:
for x in range(5):
if x == 3:
continue
print(x)Output:
0
1
2
4
As we can see in the example above, we are executing our continue statement when our x variable is 3. Looking at the output, we see that we successfully completed the iteration of all the other values besides 3. This verifies that we have successfully stopped the iteration where x was equal to 3 and continued onto the next iteration.
Example: While Loop
Now, let’s see an example of us using the continue statement in a while loop:
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)Output:
1
2
4
5
Similar to the for loop example, we are executing our continue statement when our x variable is equal to 3. We can see in the output that we have successfully completed the iterations of all the other values besides 3. This verifies that we have successfully stopped the iteration where x was equal to 3 and continued onto the next iteration.
Conclusion
This is it for the continue statement examples. It’s a statement that is used to stop a current iteration of a loop and continue onto the next iteration. I hope this helps. Thanks for reading.