首页 > 解决方案 > 棘手的python控制流

问题描述

我正在做一个项目,并通过一个简单的例子复制了我的疑问。我无法理解以下 python 代码片段的控制结构。

list1 = [1,2,3,4,5]
for item in list1:
    if item == 3:
        print("Found")
        # break
else:
    print("Not found")

注意:请注意,else 部分的缩进是故意保留的,我认为它会出现错误,但它给出了以下输出:

Found
Not found

此外,如果我们取消注释“#break ,则输出为:

Found

为什么这段代码没有抛出错误。如果它按照 if else 条件工作,那么预期的输出应该是:

Not Found
Not Found
Found
Not Found
Not Found

标签: pythonif-statementcontrol-flow

解决方案


代码中的else条件是针对for循环而不是来自 if 语句,因为您最终会得到Not found,因为它是在最后一次for循环迭代之后执行的。
在这段代码中,缩进的elseif

list1 = [1,2,3,4,5]
for item in list1:
    if item == 3:
        print("Found")
        # break
    else:
        print("Not found")

并且输出

Not found
Not found
Found
Not found
Not found

推荐阅读