When working with loops in Python, there may be situations where you want to skip a part of the loop and continue with the next iteration. This is where the continue
keyword comes in handy. In this article, we will explore how to use the continue
keyword in Python to skip code and continue with the loop.
Using the continue keyword inside a for loop
The continue
keyword is used to skip the current iteration of a loop when a particular condition is met. Let’s take a look at an example:
for i in range(1, 6): if i == 3: continue print(i)
The output of the code above will be:
1 2 4 5
As you can see, the continue
keyword skipped the number 3 and continued with the rest of the loop.
Using the continue keyword inside a while loop
The continue
keyword can also be used inside a while loop. Here is an example:
i = 0 while i < 5: i += 1 if i == 3: continue print(i)
The output of the code above will be:
1 2 4 5
As you can see, the continue
keyword skipped the number 3 and continued with the rest of the loop.
Using the continue keyword with nested loops
The continue
keyword can also be used with nested loops. Let’s take a look at an example:
for i in range(1, 4): for j in range(1, 4): if i == 2: continue print(i, j)
The output of the code above will be:
1 1 1 2 1 3 3 1 3 2 3 3
As you can see, the continue
keyword skipped the second iteration of the outer loop and continued with the rest of the loops.
Conclusion
In this article, we learned how to use the continue
keyword in Python to skip code and continue with a loop. We saw how to use it inside for and while loops, as well as with nested loops. The continue
keyword is a powerful tool when working with loops in Python, and can help you optimize your code and improve its readability.