Table of Contents
💡TL;DR
To skip iterations in Python loop, usecontinue
statement.
1234567891011 x = 0for x in range(3):if x == 1:continue #Use of the continue statementprint('Working on ' + str(x))##Output:# Working on 0# Working on 2
Looping is one of the fundamentals in Python with one or more types of loops occurring in almost every code. The for
loop and the while
loop allow the reiteration of tasks in a super-efficient way. However, there are various scenarios in which we may want to skip certain iterations in a loop.
Skip iterations in a Python loop.
This tutorial demonstrates how to skip iterations in a Python loop in an effective manner.
Using the continue
statement.
The continue
statement is one of the sets of statements along with the break
and the pass
statements that have been borrowed from the C
programming language.
The continue
statement provides a way to skip a certain part of the loop without impacting the rest of the contents of the loop. This means that the other statements will not be disrupted and the loop will simply return to the beginning or the top.
The continue
statement is generally utilized to skip certain conditions and generally goes well beside the conditional if statement.
The following code uses the continue
statement to skip iterations in a Python loop.
1 2 3 4 5 6 7 8 |
x = 0 for x in range(5): if x == 2: continue #Use of the continue statement print('Working on ' + str(x)) print('Exiting the loop') |
Output:
Working on 1
Working on 3
Working on 4
Exiting the loop
As we see from the above code that when the number 2
is encountered, the iteration is skipped and we skip to the next iteration without disrupting the flow of the code.
Special Case: Using exception handling.
Exception handling is done with the try
and the catch statements
in Python. Exception handling is utilized to pass through certain statements in the chunk of code that may produce an error. This is done usually in cases where the code is syntactically correct but it still raises an error somehow.
A try…catch statement can help in neglecting an error and proceeding regardless with the next iteration of the code.
The following code uses exception handling to skip iterations in a Python loop.
1 2 3 4 5 6 7 8 9 10 |
def xyz(): a=int(input('Enter an integer only :')) return a for i in range(5): try: print('The entered number :',xyz()) except: pass |
Output:
Enter an integer only :
In this case, we make use of the pass
statement along with exception handling in order to implement the task of skipping a certain iteration in a Python loop.
That’s all about how to skip iterations in Python loop.