这是一个有点令人困惑的问题,但这是我的(简化)代码。
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 语句?
你不能打破一个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语句终止时。
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |