Python: How to get more control when using a for loop?

I have the following code snippet, so although there is an exception, repeat this loop, rather than moving on to the next loop. Note that the pseudo code here works as intended:

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

My initiative was that as soon as something goes wrong, do it again. Obviously, this is not a working idea. So, given the assumption that the for and range function loops are used, how do I implement the control I described?

thanks

+4
source share
3 answers

You just need the second loop inside the first to continue working on 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 
+6
source

For more control over the loop variable, you can use the while :

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

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

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

+4
source

Since I have a pathological hatred of while True loops, I suggest this simplification of @kindall's answer: first, change some_function() so that it returns False on failure, instead of throwing an exception. Then use the following loop:

 for cl in range(0, 10): while not some_function(cl): pass 

If you cannot (or do not want) change some_function() , you can add a wrapper:

 def exceptionless_function(arg): try: some_function(arg) return True except <known exceptions>: return False 

EDIT: I added <known exceptions> above to indicate that an unqualified except clause should be avoided. If you don't know what types of exceptions you actually expect to catch, then simply calling the function again is almost certainly a misnomer in some cases. For example, the OP mentions (in a comment) that there will be a β€œwarning” if a timeout occurs during the retry of this function. If this warning takes the form of some kind of exception, then it will simply be ignored in the case of "just"!

+2
source

All Articles