2

it is possible to not increment count in for loop in case an error happen, like this example

for i in range(10):
    try:
        print(i)
    except: # if and error happen in i == 5 the next iteration will be 5 not 6 
        pass

I want to repeat the same iteration when the error happen. And thanks in advance.

6
  • Don't use range() if you want more control over how it increments. Commented Nov 24, 2021 at 22:55
  • Since a for loop in python is technical a foreach loop, you should change your loop to a while loop to have more control. Commented Nov 24, 2021 at 22:57
  • It's not necessary I use range() it's just example it could be list. Commented Nov 24, 2021 at 22:57
  • I ask if there is a way in for loop Commented Nov 24, 2021 at 22:58
  • Do you need it to be executed only 10 times including erros or repeat each iteration until it doesn't throw an error? Commented Nov 24, 2021 at 23:01

3 Answers 3

2

When you use for...in there's no way to avoid going to the next item in the iteration when the loop repeats.

You can use a nested loop to keep trying with the same value of i until you don't get an error:

for i in range(10):
    while True:
        try:
            print(i)
            break
        except:
            pass
Sign up to request clarification or add additional context in comments.

Comments

1

Since Python's for loop is technically a foreach loop you should use a while instead of for for more control.

i = 0
while i<10:
    try:
        #Do stuf
        i += 1
    except:
        pass

If an error happens before i += 1 it will not be incremented.

Comments

0

Maybe wrap all into a while loop:

for i in range(10):
    while True
        try:
            # whatever you have to do
            print(i)
            break
        except: 
            pass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.