Python 3 – continue statement
Python is a high-level language that is widely used to create applications and games. Python offers many functionalities, and one of them is the continue statement, which allows you to skip a particular iteration of a loop without terminating it entirely. In this article, we will explore the use of the continue statement and its syntax in Python.
for i in range(1, 6): # Here, we are using the range function to loop through the range 1 to 5
if i == 3:
continue # When i == 3, we will skip this iteration and move on to the next iteration.
print(i) # Print whatever the value of i is for each iteration.
The above code will output:
1
2
4
5
From the above code, we can see that the continue statement allows us to skip a particular iteration (when i == 3
) and move to the next one. This is particularly helpful when we want to skip a particular iteration and continue with the rest of the loop.
Syntax of the continue statement
The syntax of the continue statement is quite simple. It is a single keyword that is used inside a loop. When the continue statement is executed, it skips the current iteration and moves on to the next one. The syntax is as follows:
continue
As mentioned earlier, the continue statement is used inside a loop. The loop can be a while
loop or a for
loop.
Example
Let’s take an example where we use the continue statement inside a while
loop.
i = 1
while i <= 5:
if i == 3:
i += 1 # Don't forget to increment i, or you'll end up with an infinite loop
continue # Skip when i == 3
print(i)
i += 1 # Increment i after printing
The above code will output:
1
2
4
5
Here, we are using a while
loop instead of a for
loop. We start with i
equal to 1 and keep printing its value until it reaches 5. However, when i == 3
, we skip that iteration and move on to the next one using the continue statement.
Conclusion
In conclusion, the continue statement is an important keyword in Python that helps you to skip a particular iteration of a loop. This allows you to continue with the rest of the loop without terminating it entirely. It is particularly helpful when you want to skip over certain values in a loop that you are not interested in. The syntax of the continue statement is quite simple, and it is used inside a loop. You can use it with both while
and for
loops.