In the previous article we explored the utility of the Break function, now we will explore the continue function in Python. Let us take a look at an illustrative problem and example: We are given a list of numbers, and we need to print out only those values from the list which are not the multiples of 5. In the list l= [10,16,17,18,19,15] . If we pass this data to such a program it should exclude the values of 10 and 15. In the list l= [13,14,12,10,11] we would need to return the values 13, 14, 12, and 11.
Working with the continue function in Python
The continue function is very useful in such situations, once the continue function is executed it tells the program to continue with the next iteration of the loop and to ignore the statements below the continue function.
l= [10,16,17,18,19,15]
for x in l:
if x % 5 == 0:
continue
print(x)
Output:
16
17
18
19
Let us look at another example:
i=0
while i<=5:
if i=-3:
i=i+1
continue
print(i, i*i)
i=i+1
Output:
0 0
1 1
2 4
4 16
5 25
l=[10,16,17,18,9,15,21,13]
for x in l:
if x%5==0:
continue
if x%7==0:
break
print(x)
print("Bye")
Output:
16
17
18
9
Bye
Hence, we have explored the use of the continue function. In the next article we will explore nesting of loops with one another.