Python - 在 if 语句中的 for 循环中跳出 if 语句

a66*_*623 1 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')
Run Code Online (Sandbox Code Playgroud)

问题是,如果some condition满意(即打印 x),我不希望打印“未找到”。如何突破最外层的 if 语句?

che*_*ner 5

你不能打破一个if声明;但是,您可以使用循环的else子句for有条件地执行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')
Run Code Online (Sandbox Code Playgroud)

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