python - 为什么 "else"子句的目的是在 "for"或 "while"循环之后?

标签 python python-3.x

我是Python初学者。我发现elsefor -elsewhile -else完全没有必要。因为forwhile最终会运行到else ,我们可以使用通常的线路来代替。

例如:

for i in range(1, 5):
    print i
else:
    print 'over'

for i in range(1, 5):
    print i
print 'over'

是一样的。

那么为什么Python有elsefor -elsewhile -else

最佳答案

您对 for/else 的语义有误。 else 子句仅在循环完成时运行,例如,如果未遇到break 语句。

典型的 for/else 循环如下所示:

for x in seq:
    if cond(x):
        break
else:
    print "Didn't find an x I liked!"

将“else”视为与循环体中的所有“if”配对。您的示例是相同的,但是混合了“break”语句,它们就不同了。

同一想法的更长描述:http://nedbatchelder.com/blog/201110/forelse.html

关于python - 为什么 "else"子句的目的是在 "for"或 "while"循环之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55722755/

相关文章:

python - 如何在 glob() 模式中写入 "or"?

python - 在Python3中使用Selenium和Requests模块从网页获取文件

python - 使用 WSL 的 python virtualenv 中没有 lib64 目录

python - 如何让pandas显示每个数据行

python - 使用PyInstaller编译后是否还需要安装python项目依赖?

python - 制作一个简单的《太空侵略者》克隆——pygame.time.delay 导致崩溃

python - 为什么这个双循环不起作用?

python - 强制 Nosetests 使用 Python 2.7 而不是 3.4

python - 为什么纹理索引 31 在 Moderngl 中被覆盖?

python - Unicode Objects must be encoded before hashing 错误