[英]How to go back to the beginning of a loop in python if error?
如果像这样在 python 中出现一些错误,我想 go 开始一个“for”循环。
for i in ~:
try:
---code---
except ~Error:
# go back to the beginning of loop
# do the next thing
您可以在 while 循环中运行 for 循环。
while condition:
for index in iterable:
try:
--code--
except Exception:
break
为此,您应该查看while
语句。
例如:
i=1
while i < n:
if something:
do something
i += 1
else:
do something else
i = 2 #loop restart
有两个选项可以做某事,还有“循环重启”
您也可以尝试continue
据我所知,没有简单的方法可以完成您在 Python 中提出的要求(如果我理解正确的话)。 话虽如此,为了模拟该功能,我建议在增加索引变量之前使用while
循环和continue
语句。
像这样的东西:
some_number = 10 # any number
i = 0
while i < some_number:
try:
do_something(i) # might err
except:
continue
i += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.