Loop Control System

Learn how to control loops through special statements.

We'll cover the following

All programming languages have loop control statements that can change the flow of execution in a program from the normal sequence.

Continue

The continue statement returns the control to the beginning of the loop or, in other words, the flow control continues with the next iteration of the loop. In the following example, the normal sequence of flow control should be: for each number in the list, check if it is less than or equal to 5, then print it; if it is greater than 5, print it with a different string.

for n in [1,2,3,4,5,6,7,8,9]:  
    if n <= 5:
        print(n,'is less than equals to 5')
    else:
        print(n,'is greater than 5')

Imagine, however, a use case where we want to print only the numbers greater than 5. Either we can use an if statement to filter only those numbers, or we can add a continue statement to our previous example to change the flow control to return to the beginning of the loop if a number smaller than 5 is found. This will result in only numbers greater than 5 being returned.

Get hands-on with 1200+ tech skills courses.