How to skip Iterations in a Python loop?

Loops are one of the most important terms in any programming language with this particular concept recurring in almost every Python code. With the existence of loops, comes the problem to skip iterations in a Python loop.

The for loop and the while loop being the most used ones and they proceed to successfully attempt the reiteration in an ultra-efficient manner. However, sometimes you might need to skip certain iterations of a loop based on certain conditions.

This tutorial demonstrates the different ways available on how to skip iterations in a Python loop.

Using the continue statement.

The continue statement is used to skip a single iteration in a loop. When the continue statement is encountered, the current iteration is stopped, and the loop immediately moves on to the next iteration. You would be able to understand this in more details after taking a look at the below example.

The upside of using the continue statement is that it provides a way to skip a certain part of the loop without impacting the rest of the contents of the loop.

Consider the following code:

a= 0
for a in range(5):
  if a == 4:
    continue   #Use of the continue statement
  print('Print number ' + str(a))
print('Automatic loop Termination')
"""Output:
Working on 0
Working on 1
Working on 3
Working on 4
Exiting the loop
"""

Similarly, the continue statement can also be utilized in a while loop. The while loop operates a bit differently as it checks the condition before each iteration, and the loop continues to run as long as the condition is true.

Consider the following code, where the loop will print all odd numbers from 1 to 20, but skip even numbers.

a = 1
while a <= 20:
    if a % 2 == 0:
        a += 1
        continue
    print(a)
    a += 1
"""Output:
1
3
5
7
9
11
13
15
17
19
"""

Using the return statement.

The return statement is used to exit a function and return a value. Exiting a function inside a loop is also one of its uses.

Here’s an example of how to use the return statement in a loop:

def find_index(lst, target):
    for i, item in enumerate(lst):
        if item == target:
            return i
    return -1
lst = [1, 2, 3, 4, 5]
target = 3
print(find_index(lst, target))
#Output: 2

In this example, the loop will search for the target value in the list, and return the index of the target if found. The loop exits and returns the result as `-1` if it does not find the target during its run.

Special Case: Using exception handling with the pass statement.

The try and catch statements are utilized for implementing the process of exception handling in Python.

Exception handling is utilized to slide past certain statements in a certain part of the code that have a probability of producing an error. These rare cases are the parts of the program where the code is syntactically correct but an error might still arise somehow.

A try...catch statement helps in proceeding ahead by ignoring the error that might be encountered along the way.

Consider the following code.

def entint(): 
     x=int(input('Please enter an integer only :')) 
     return x 
for i in range(5): 
    try: 
        print('The number you entered :',entint()) 
    except: 
        pass 
"""Output:
Please enter an integer only : w
Please enter an integer only : 
"""

The pass statement is utilized here along with exception handling to implement the task at hand.

To Conclude.

Python provides several ways to skip iterations in loops based on certain conditions. These techniques make your code more efficient and effective, while also helping in saving time and resources in your programs. By understanding the different ways to skip iterations in a loop, you can improve your Python programming skills and write better code.

Explore more from this category at Python Loops. Alternatively, search and view other topics at All Tutorials.

1 thought on “How to skip Iterations in a Python loop?”

  1. Pingback: How to end the while loop in Python? - Educate Python

Comments are closed.