看到用了 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
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.