Python在if语句的for循环中中断if语句

2024-03-28 15:45:33 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个有点混乱的问题,但这里是我的(简化)代码

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语句


Tags: 代码inforstringifstatusnotcode
3条回答

事实上,语言中有一种通用的机制可以打破任何障碍,你抛出一个hissy-fit,也就是异常;只要确保你抓住它,恢复你的流动。 这完全取决于您所处的环境(编码标准、性能等)

它不像标签那样干净&;在一些语言中,跳转/跳转,但我不介意

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

为什么不直接使用变量呢

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')

你不能突破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')

print仅当for循环在s_list上迭代时被StopIteration异常终止时才会调用,而不是,如果它被break语句终止

相关问题 更多 >