棘手的python控制流

棘手的python控制流,python,if-statement,control-flow,Python,If Statement,Control Flow,我在做一个项目,用一个简单的例子重复了我的疑问。我无法理解以下python代码片段的控制结构 list1 = [1,2,3,4,5] for item in list1: if item == 3: print("Found") # break else: print("Not found") 注意:请注意,else部分的缩进是故意保留的,我认为这可能是由于一个错误,但它给出了以下输出: Found Not

我在做一个项目,用一个简单的例子重复了我的疑问。我无法理解以下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

代码中的
else
条件用于
for
循环,而不是来自if语句,因为您最终得到
not found
,因为它是在上次
for
循环迭代之后执行的。
在此代码中,
else
的缩进用于if

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

为了更清楚地理解它,为if块放置另一个else循环。。。当前else块用于for循环

Python
for
循环可以有一个
else
子句。见