It is possible to not increment count in for loop - Python - python

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.

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

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

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.

Related

How to break the While True statement on the same error 3 times

I'm currently using the while True loop, but if the same error is repeated 3 times, please tell me how to exit the while True statement. I use python.
You can add a variable keeping track of the last error's type, and a counter for the how many of those occurred, which resets if an error of a different type appeared. If the counter hits 3, then exit accordingly.
last_exception, counter = None, 0
while True:
try:
# some error here
raise ValueError
except Exception as e:
if type(e) is not last_exception:
last_exception, counter = type(e), 0
counter += 1
if counter == 3:
break
You just declare a variable outside your loop and initialize to 0, increment it by one each time the loop iterates, and your while loop iterates while it's less than 3
i = 0
while i < 3:
print(i)
i += 1
Edit: I just realised you said while true
Take a look at this
What does "while True" mean in Python?
If you have to use a while true then use an if statement to check if i >=3 and then use a break statement to exit the loop if that's true

Get stuck in a 'while True' loop python

I just learned about break and return in Python.
In a toy code that I wrote to get familiar with the two statements, I got stuck in a loop, but I don't know why. Here is my code:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
I'm new to programming, any suggestions will be appreciated.
With the for-else construct you only enter the else block if the for loop does not break, which your for loop always does because i inevitably becomes 3 with your range generator. Your infinite while loop is therefore never able to reach the return statement, which is only in the said else block.
nvm I'm super wrong here
First of all, when you define a function in Python, any code that belongs in the function should be in the same indentation block. With this in mind, your code would look like this:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
The next problem I see is that your else statement isn't correctly formatted with an if statement. If you mean for it to go on the 2nd if statement, your code would look like this:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
This is only formatting. But in this example, the code would only run once because it immediately returns and exits the function.
I think this may be a better example of using both break and return:
def break_return(value):
for i in range(5):
print(i)
if i == 3:
break #This exits the for loop
if i == 4:
print("This won't print!")
#Won't print because the loop "breaks" before i ever becomes 4
return value * 2 #Returns the input value x 2
print(break_return(30)) #Display the return value of break_return()
This demonstrates how break exits a for loop and how return can return a value from the function.
The output of the code above is:
0 #Value of i
1 #Value of i
2 #Value of i
3 #Value of i
60 #The value returned by the function
Glad to hear you're learning Python! It's a lot of fun, and super useful.

Re-execution of for loop when exception occured from current position in Python

I want to do something like shown below for my project.
whenever any exception will occur I want to start the for loop from current position of 'i'
for eg:
if exception occured at i=3 then my for statement should again start from i=3 till end
Example
for i in range(5):
try:
# some code
except Exception as e:
restart_for_loop_from_current i
Thanks in advance
You could use a nested loop. Something like this would work:
for i in range(5):
loop = True
while loop:
try:
# some code
loop = False
except Exception as e:
# some code make sure this while loop is not endless
pass
Why not change the for-loop to a while-loop? Just increment the variable when no exception occurred, something like this:
while i < 5:
try:
# loop operations
i = i + 1
except:
error = error + 1
# error handling code

how to exit try loop after code succeed?

my code below tries to execute a function x but because x takes time to build, i need to sleep until it is built then call it. So it usually takes me about 300s to build. When i run the code below, it will loop through the try loop about 3 times but print 0 every time it pass through the except code.
Is it right to put the print x (for when code succeeds and i break) outside the for loop like below or somewhere else? Also, how do i make i print the number of time it is trying instead of 0?
for i in range(0,10):
while True:
try:
x = my_get_fuction
except:
print "error"
print i
time.sleep(100)
continue
break
print x
Your while loop doesn't seem to be related to your design. Try this:
for i in range(0,10):
try:
x = my_get_fuction
except:
print "error"
print i
time.sleep(100)
continue
break
print x
This code will loop a maximum of 10 times, sleeping each time for 100s. If the assigned x = my_get_function doesn't complete by 1000s or so, then the loop gives up.

Can you "restart" the current iteration of a Python loop?

Is there a way to implement something like this:
for row in rows:
try:
something
except:
restart iteration
You could put your try/except block in another loop and then break when it succeeds:
for row in rows:
while True:
try:
something
break
except Exception: # Try to catch something more specific
pass
You could make rows an iterator and only advance when there is no error.
it = iter(rows)
row = next(it,"")
while row:
try:
something
row = next(it,"")
except:
continue
On a side note, if you are not already I would catch specific error/errors in the except, you don't want to catch everything.
If you have Falsey values you could use object as the default value:
it = iter(rows)
row, at_end = next(it,""), object()
while row is not at_end:
try:
something
row = next(it, at_end)
except:
continue
Although I wouldn't recommend that, the only way to do this is to make a While (True) Loop until it gets something Done.
Bear in mind the possibility of a infinite loop.
for row in rows:
try:
something
except:
flag = False
while not flag:
try:
something
flag = True
except:
pass
Have your for loop inside an infinite while loop. Check the condition where you want to restart the for loop with a if else condition and break the inner loop. have a if condition inside the while loop which is out side the for loop to break the while loop.
Like this:
while True:
for row in rows:
if(condition)
.....
if(condition)
break
if(condition)
break
Try this
it = iter(rows)
while True:
try:
something
row = next(it)
except StopIteration:
it = iter(rows)
My 2ยข, if rows is a list, you could do
for row in rows:
try:
something
except:
# Let's restart the current iteration
rows.insert(rows.index(row), row)
continue # <-- will skip `something_else`, i.e will restart the loop.
something_else
Also, other things being equal, for-loops are faster than while-loops in Python. That being said, performance is not a first order determinant in Python.
I think user2555451's answer does it pretty well. That being said, you should use continue instead of pass as it will make sure the while True loop is restarted.
for row in rows:
while True:
try:
...
break
except Exception:
continue
I will explain it for newer Python users:
break only breaks the loop you're working in. So if you have something like this: (the variables and functions are imaginary)
for x in imgWidth:
for y in imgHeight:
if ...:
break
drawPixel(x, y, "#FF0000")
and you somehow want to skip a pixel, you can break the loop as it will return to the previous level. The same is true for continue.
Now back to the example:
for row in rows:
while True:
try:
...
break
except Exception:
continue
You move any code you would like to run inside the try block. It will try to do it, and if it catches an error, it will retry because we continue the while True loop! When it finally does the code without errors, it breaks and now it's back in the for loop. Then it continues to the next iteration as it has nothing left to do.
Here is a simple version without using nested loops, an infinite while loop, or mutating the original iterator. Also, it controls the number of attempts with a max_retry parameter:
def do_something(retry=0, max_retry=4):
try:
print('something')
except Exception as e:
if retry == max_retry:
print(f"Max retries reached!")
raise e
do_something(retry=retry + 1)
do_something()

Categories