Python, for-else, while-else是否造成了语义歧义 ( 增加心智负担 )?
PHP中文网
PHP中文网 2017-04-18 10:28:27
[Python讨论组]

看到用了 for-else/while-else的代码, 往往不能马上搞懂 else 处代码的意思

因为, 脑袋不能马上反应, else 到底表示了什么样的语义( 还需要转几个弯 )

(但是 try - except -else 没有带来语义上的歧义)

相关代码

  • 能否一眼辨别出, 什么时候, 什么条件下 else处代码会执行?

for i in range(5):
...     print(i)
... else:
...     print('Iterated over everything :)')


for i in range(5):
...     if i == 2:
...         break
...     print(i)
... else:
...     print('Iterated over everything :)')


for i in []:
...     print(i)
... else:
...     print('Still iterated over everything (i.e. nothing)')



> i = 0
>>> while i <= 5:
...     i += 1
...     print i
... else:
...     print 'Yep'



for x in data:
    if meets_condition(x):
        break
else:
    # raise error or do additional processing 
PHP中文网
PHP中文网

认证0级讲师

全部回复(4)
巴扎黑

题主认为语义不明是可以理解的。毕竟其他语言中的 else 只跟 if 搭配,更何况这里的 else 并不符合自然语义。

在自然语义下,else 有 "其它的" 的意思,但对 for, while, try 型 else,用 "除了以上程序考虑到的情况" 来解释此子句并不合理。私以为理解成 "主块正常结束后的情况" 更为正确——所谓主块,即 else 附属的 循环体 或 try 子句; 所谓正常,即不通过特殊手段中止控制流(异常 或 循环中的 break)。

这么理解可能更清晰些。

伊谢尔伦

我喜欢这个例子:

n = 17
for d in range(2,n):
    if n % d == 0:
        print(n, '是合数')
        break
else:
    print(n, '是素数')

没有else的话我们应该加个bool变量,for循环后还加个if/else。用for/else的话简单多了。你慢慢会熟悉;-)

怪我咯

没有歧义,你不习惯而已。

PHPz

Fluent Python的作者认为是会增加的,他这样说到:I think else is a very poor choice for the keyword in all cases except if. It implies an excluding alternative, like “Run this loop, other‐ wise do that”, but the semantics for else in loops is the opposite: “Run this loop, then do that”. This suggests then as a better keyword — which would also make sense in the try context: “Try this, then do that.” However, adding a new keyword is a breaking change to the language, and Guido avoids it like the plague.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号