Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to gain more control while using 'for' loop?

I have got the following piece of code, so that while any exception occurs, re-do this loop, instead of jumping to the next loop. Please note the pseudo code here does work as intended:

for cl in range(0, 10):
    try:
        some_function(cl)
    except :
        cl -= 1

My initiative was that once something go wrong, do it again. Obviously, this is not a working idea. So given the assumption that the for loop and range function being used, how to implement the control that I described?

Thanks

like image 822
Chen Xie Avatar asked Dec 16 '22 16:12

Chen Xie


2 Answers

You simply need a second loop inside the first to continue trying the function until it works:

for cl in range(0, 10):
    while True:
        try:
            some_function(cl)
        except Exception:
            continue    # try it again
        else:
            break       # exit inner loop, continue to next c1
like image 180
kindall Avatar answered Jan 05 '23 00:01

kindall


For more control over the loop variable, you might want to use a while loop:

cl = 0
while cl < 10:
    try:
        some_function(cl)
        cl += 1
    except:
        pass

In Python, the pass statement is a "do-nothing" placeholder. In the case where you get an exception, the same cl value will be tried again.

Of course, you will also want to add some mechanism where you can exit the loop if you always get an exception.

like image 37
Greg Hewgill Avatar answered Jan 04 '23 23:01

Greg Hewgill