[英]Python - Break out of if statement in for loop in if statement
這是一個有點令人困惑的問題,但這是我的(簡化的)代碼。
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),我不希望打印“未找到”。 如何突破最外層的 if 語句?
你不能跳出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
異常終止時才會調用print
,而不是由break
語句終止時調用。
為什么不只使用變量?
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')
實際上,語言中有一個通用的機制可以打破任何塊,你拋出一個嘶嘶聲,也就是異常; 只要確保你抓住它並恢復你的流程。 這完全取決於您所處的環境(編碼標准、性能等)。
在某些語言中,它不像 LABELS & JUMP/GO_TO 那樣干凈,但確實有效,我不介意。
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:
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.