In this article, we will be covering "continue" keyword within FOR loops in Python.
In Python, in order to iterate through a list, we had used FOR loop in earlier articles. Lets assume that we need to skip a cycle or iteration when we find a specific value within loop. To achieve that, "continue" keyword can be used. Continue keyword causes loop to reset itself and go for next cycle. Lets look at syntax of using continue in a python FOR loop:
x=0
for index in range(5):
x +=1
if(x==2):
continue
print("x reached 2")
print(x)
Output of above using continue in a FOR loop in Python:
In above Python example, we first declared a variable called x and set it to 0. We declared a surrogate variable called index and called it 5 times with range function in Python (that generates a list in backscene). Each iteration increased value of x by 1. Within loop, we check condition to evaluate: if value is 2, we are teling loop to go out of loop for that cycle and start next cycle.
As the result, loop does not value of 2 but keeps printing remaining values.