Python continue Explained [Beginners Guide]

What does continue statement do in python?

In Python continue statement is used to continue executing a next iteration of for loop or a while loop when certain condition is satisfied rather than executing the normal flow of loop. Note that continue statement will skip the remaining statement of current iteration and continue with next iteration.

The continue statement is widely used to control the program flow in presence of certain conditions. The syntax of continue statement when used with for loop or while loop is as shown below.

Advertisement

 

How python continue statement is different than other languages?

Whether in Python, C, Java, or any other structured language that features the continue statement, there is a misconception among some beginning programmers that the traditional continue statement “immediately starts the next iteration of a loop.

While this may seem to be the apparent action, we would like to clarify this somewhat invalid supposition. Rather than beginning the next iteration of the loop when a continue statement is encountered, a continue statement terminates or discards the remaining statements in the current loop iteration and goes back to the top. If we are in a conditional loop, the conditional expression is checked for validity before beginning the next iteration of the loop. Once confirmed, then the next iteration begins. Likewise, if the loop were iterative, a determination must be made as to whether there are any more arguments to iterate over. Only when that validation has completed successfully can we begin the next iteration.

 

Some practical examples

Example-1: Using continue in while loop

The example here iterates over the range of numbers from 1 to 10 and prints its value. However, if it reaches the number divisible by 5, it will continue with the while loop without printing the number.

# Initializing
i=1

# Iterating while loop
while i <= 10:
    # loop skips printing if the value of i reaches number divisible by 5
    if(i%5==0):
        i+=1
        continue
    print(i)
    i+=1
else:
    print("Ending of while loop")

Output

1
2
3
4
6
7
8
9
Ending of while loop

 

Example-2 - Using continue in for loop

When you want to iterate over the sequence one way is to iterate using the for loop given below that gives the position of the desired element. Here, we are performing linear search to search the element whose value is "China". The example below iterates over the list of countries and skips "China" while printing the other countries.


# Initializing
l1=['India','Nepal','Srilanka','China','Australia']
for country in l1:
	if country == 'China':
		continue
	else:	
		print (country)

Output

Advertisement
India
Nepal
Srilanka
Australia

 

Example-3 - Find sum of positive numbers given as input

In the example given below, We will use if else condition to evaluate the input which we are taking from the user. When user inputs positive number, it gets added to the sum. Whereas, when input is a negative number, loop simply continues without adding the input to the existing sum. However, while loop terminates when the input is -1.

# Initializing
sum=0
i=0
while (i != -1):
    i=int(input("Enter a positive number. Input -1 to exit"))
    if(i<0 and i != -1):
        i=0
        continue
    if(i == -1):
        break
    sum = sum + i
    print("Sum is ",sum)
    

Output

Enter a positive number. Input -1 to exit
10
Sum is  10
Enter a positive number. Input -1 to exit
20
Sum is  30
Enter a positive number. Input -1 to exit
2
Sum is  32
Enter a positive number. Input -1 to exit
-2
Enter a positive number. Input -1 to exit
5
Sum is  37
Enter a positive number. Input -1 to exit
-1

 

Example-4 - Constructing Dictionary from two list

In the example given below, We have two list containing the name of students and their score respectively. Here, we will read the value from the two lists and construct the dictionary out of this lists with the condition that if the score is found to be less than 50 for a particular student, We will skip that value and continue with the next student.

l1=['Ram', 'Rohan', 'Rishi', 'Radha']
l2=[82,42,95,60]
d={}
i=0
while i < len(l1) and i < len(l2): 
    if(l2[i] < 50):
        i+=1
        continue
    d.update({l1[i]:l2[i]})
    i+=1
else:
    print("Dictionary constructed successfully")
print("Retrieving values from Dictionary")
print(d)

Output

Dictionary constructed successfully
Retrieving values from Dictionary
{'Ram': 82, 'Rishi': 95, 'Radha': 60}

 

Example-5 - Using continue in for loop inside another while loop

In the example given below, we will print the strings stored in the python list using the while loop and iterate over the list using for loop. Once, we encounter $ symbol in the particular string of a list, we will simply skip that character and continue with the next character of same word.

# Initializing
s=['Welcome', 'to', 'the', 'world', 'of', '$dollar', 'Python']
# iterate loop till the last character
for word in s:
    i=0
     # Iterating word by word
    while i < len(word):
    # continue loop with next character if current character is dollar $ 
        if word[i]== '$':
            i=i+1
            continue
    # print current character
        print(word[i], end=' ')
        i = i + 1

Output

Advertisement
W e l c o m e t o t h e w o r l d o f d o l l a r P y t h o n

 

Example-6 - Using multiple continue statement

In the example given below, we are using while loop to print the pattern of numbers while skipping the number 7. So, here each number gets printed that number times skipping the row 7.

a = 1
count = 0
while( a <= 10 ):
    if (count < a):
        print(a,end=' ')
        count+=1
        continue    
    if(count==6):
        count+=1
        a+=1
        continue
    if (count == a):
        print("\n")
        a+=1
        count = 0

Output

1 

2 2 

3 3 3 

4 4 4 4 

5 5 5 5 5 

6 6 6 6 6 6 

8 8 8 8 8 8 8 8 

9 9 9 9 9 9 9 9 9 

10 10 10 10 10 10 10 10 10 10

 

Example-7 - Using continue statement in nested for loops

In this example, we are printing the list containing tuples such that we will not process the tuple with more than 2 elements and also if the value of tuple is 3.

l = [(1, 2), (3, 4), (5, 6, 7),(8,9)]
for t in l:
    # don't process tuple with more than 2 elements
    if len(t) > 2:
        continue
    for i in t:
        # don't process if the tuple element value is 3
        if i == 3:
            continue
        print('Value of i is  ',i)

Output

Value of i is   1
Value of i is   2
Value of i is   4
Value of i is   8
Value of i is   9

 

Example-8 - Using continue statement in nested while loop

In this example, we are using two while loops to restrict the number of rows and the values in number of rows skipping the odd numbers respectively.

i = 1
while i < 6 :
    j = 1
    while j < 10 :
        // check if remainder is 1
        if j % 2 == 1 :
            // increment by 1 and continue with while loop
            j += 1
            continue
        print(i*j, end=" ")
        j += 1
    print()
    i += 1

Output

Advertisement
2 4 6 8 
4 8 12 16 
6 12 18 24 
8 16 24 32 
10 20 30 40

 

Summary

The knowledge of control flow statement continue is core to python programming language that is very useful to formulate a complex logic easily. You will frequently need to use the continue statements  to prevent execution of block for certain set of values and build varied of applications. The knowledge of continue in different scenarios and combinations helps solving the really complex task to a time efficient solution. In this tutorial, we covered the continue statement with for loop, while loop, nested loops and different combinations of the loops along with an example to demonstrate the functionalities of continue statement. All in all, this tutorial, covers everything that you need to know in order to understand and use the continue in Python.

 

References

Control Flow statement

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X