Python, for-else, while-else是否造成了語義歧義 ( 增加心智負(fù)擔(dān) )?
問題描述
看到用了 for-else/while-else的代碼, 往往不能馬上搞懂 else 處代碼的意思
因?yàn)? 腦袋不能馬上反應(yīng), else 到底表示了什么樣的語義( 還需要轉(zhuǎn)幾個(gè)彎 )
(但是 try - except -else 沒有帶來語義上的歧義)
相關(guān)代碼能否一眼辨別出, 什么時(shí)候, 什么條件下 else處代碼會(huì)執(zhí)行?
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):breakelse: # raise error or do additional processing
問題解答
回答1:題主認(rèn)為語義不明是可以理解的。畢竟其他語言中的 else 只跟 if 搭配,更何況這里的 else 并不符合自然語義。
在自然語義下,else 有 '其它的' 的意思,但對(duì) for, while, try 型 else,用 '除了以上程序考慮到的情況' 來解釋此子句并不合理。私以為理解成 '主塊正常結(jié)束后的情況' 更為正確——所謂主塊,即 else 附屬的 循環(huán)體 或 try 子句; 所謂正常,即不通過特殊手段中止控制流(異常 或 循環(huán)中的 break)。
這么理解可能更清晰些。
回答2:我喜歡這個(gè)例子:
n = 17for d in range(2,n): if n % d == 0:print(n, ’是合數(shù)’)breakelse: print(n, ’是素?cái)?shù)’)
沒有else的話我們應(yīng)該加個(gè)bool變量,for循環(huán)后還加個(gè)if/else。用for/else的話簡(jiǎn)單多了。你慢慢會(huì)熟悉;-)
回答3:沒有歧義,你不習(xí)慣而已。
回答4:Fluent Python的作者認(rèn)為是會(huì)增加的,他這樣說到: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.
相關(guān)文章:
1. python的正則怎么同時(shí)匹配兩個(gè)不同結(jié)果?2. python - pymysql建立連接出錯(cuò)3. win10 python3.5 matplotlib使用報(bào)錯(cuò)4. 網(wǎng)頁爬蟲 - python 爬取網(wǎng)站 并解析非json內(nèi)容5. python小白,問一個(gè)關(guān)于可變類型和不可變類型底層的問題6. python - django中找不到css等靜態(tài)文件7. linux - python編譯ssl錯(cuò)誤8. python 匹配數(shù)據(jù)輸出數(shù)據(jù)9. python - 爬取微信公眾號(hào)文章需要輸入驗(yàn)證碼問題10. python - 調(diào)用api輸出頁面,會(huì)有標(biāo)簽出現(xiàn),請(qǐng)問如何清掉?
