python - 棘手的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
解决方案
代码中的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
推荐阅读
- javascript - 图片未在弹出窗口中显示(CSS、HTML、Javascript)
- c# - 我们可以根据登录的不同用户在c#中选择数据库连接吗?
- c# - Android 设备监视器在层次结构视图的树视图中未显示任何内容以检查 xamarin 表单 ui 性能
- firebase - 定义简单函数时谷歌云函数错误
- javascript - 使用 html onclick 提交按钮,搜索 js 数组,然后在原始 html div 中显示特定数据
- c# - ValueTuple 对于大型对象有多好?
- azure - 获取安全中心在 azure vm 上进行威胁检测的电子邮件警报
- python-2.7 - 使用 python docx 按部分交叉引用的图形编号
- python - “无法连接到 HTTPS URL,因为 SSL 模块不可用。”
- java - 无法从硒中的输入元素获取文本