这是一个有点令人困惑的问题,但这是我的(简化)代码。
if (r.status_code == 410):
s_list = ['String A', 'String B', 'String C']
for x in in s_list:
if (some condition):
print(x)
break
print('Not Found')问题是,如果some condition是满意的(即x是打印的),我不希望“Not”被打印。我怎样才能打破最外面的if语句?
发布于 2021-01-20 16:25:46
不能脱离if语句;但是,可以使用for循环的else子句有条件地执行print调用。
if (r.status_code == 410):
s_list = ['String A', 'String B', 'String C']
for x in in s_list:
if (some condition):
print(x)
break
else:
print('Not Found')只有当for循环在迭代s_list时被StopIteration异常终止时,才会调用s_list,而不是当break语句终止它时。
发布于 2021-01-20 16:25:18
为什么不直接使用变量呢?
if (r.status_code == 410):
s_list = ['String A', 'String B', 'String C']
found = None
for x in in s_list:
if (some condition):
found = x
print(x)
break
if not found:
print('Not Found')发布于 2021-01-20 18:57:21
实际上,语言中有一种常见的机制,用于突破任何块,您抛出一个异常,只需确保捕捉到它并恢复流即可。这完全取决于你所处的环境(编码-标准、性能等)。
在某些语言中,它不像标签那样干净&跳转/转到,但我并不介意。
from builtins import Exception
class JumpingAround(Exception):
def __init__(self, message=None, data=None, *args, **kwargs):
super(Exception, self).__init__(message, *args, **kwargs)
self.data = data
try: #surrounding the IF/BLOCK you want to jump out of
if (r.status_code == 410):
s_list = ['String A', 'String B', 'String C']
for x in s_list:
if (some condition):
print(x)
# break
raise JumpingAround() # a more complex use case could raise JumpingAround(data=x) when catching in other functions
print('Not Found')
except JumpingAround as boing:
passhttps://stackoverflow.com/questions/65813482
复制相似问题