Skip Iterations in Python loop

💡TL;DR
To skip iterations in Python loop, use continue statement.

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.

Output:

Working on 0
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.

Output:

Enter an integer only : a
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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *