如果發生錯誤,可以不增加 for 回圈中的計數,就像這個例子
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
我想在錯誤發生時重復相同的迭代。并提前致謝。
uj5u.com熱心網友回復:
當您使用時for...in,無法避免在回圈重復時轉到迭代中的下一項。
您可以使用嵌套回圈繼續嘗試使用相同的值,i直到您沒有收到錯誤:
for i in range(10):
while True:
try:
print(i)
break
except:
pass
uj5u.com熱心網友回復:
也許全部包裝成一個while回圈:
for i in range(10):
while True
try:
# whatever you have to do
print(i)
break
except:
pass
uj5u.com熱心網友回復:
由于 Python 的for回圈在技術上是一個foreach回圈,因此您應該使用 awhile而不是for進行更多控制。
i = 0
while i<10:
try:
#Do stuf
i = 1
except:
pass
如果之前發生錯誤i = 1,則不會遞增。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365128.html
標籤:Python
上一篇:如何洗掉pip和python
