看到用了 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
巴扎黑2017-04-18 10:30:27
The questioner believes that it is understandable that the semantics are unclear. After all, else in other languages only goes with if, not to mention that else here does not conform to natural semantics.
Under natural semantics, else has the meaning of "other", but for for, while, try type else, it is not reasonable to use "except for the circumstances considered by the above program" to explain this clause. I think it is more correct to understand it as "the situation after the main block ends normally" - the so-called main block is the loop body or try clause attached to else; the so-called normal means that the control flow is not interrupted by special means (exceptions or loops) break).
It may be clearer to understand it this way.
伊谢尔伦2017-04-18 10:30:27
I like this example:
n = 17
for d in range(2,n):
if n % d == 0:
print(n, '是合数')
break
else:
print(n, '是素数')
If there is no else, we should add a bool variable and an if/else after the for loop. It's much simpler to use for/else. You will get familiar with it gradually;-)
PHPz2017-04-18 10:30:27
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.