Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip iterations in a loop?

Tags:

python

People also ask

How do you skip loop iteration in Python?

You can use a continue statement in Python to skip over part of a loop when a condition is met. Then, the rest of a loop will continue running. You use continue statements within loops, usually after an if statement.

How do you skip a loop in Java?

The continue statement is used to skip the current iteration of the loop. break keyword is used to indicate break statements in java programming. continue keyword is used to indicate continue statement in java programming. We can use a break with the switch statement.

What function skips an iteration of a loop in R?

The next statement in R programming language is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts next iteration of the loop.


You are looking for continue.


for i in iterator:
    try:
        # Do something.
        pass
    except:
        # Continue to next iteration.
        continue

Example for Continue:

number = 0

for number in range(10):
   number = number + 1

   if number == 5:
      continue    # continue here

   print('Number is ' + str(number))

print('Out of loop')

Output:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 6 # Note: 5 is skipped!!
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop

Something like this?

for i in xrange( someBigNumber ):
    try:
        doSomethingThatMightFail()
    except SomeException, e:
        continue
    doSomethingWhenNothingFailed()

I think you're looking for continue


For this specific use-case using try..except..else is the cleanest solution, the else clause will be executed if no exception was raised.

NOTE: The else clause must follow all except clauses

for i in iterator:
    try:
        # Do something.
    except:
        # Handle exception
    else:
        # Continue doing something