Python 循环语句可能有一个 else
子句,当且仅当循环不被 break
终止时才执行该子句。换句话说,当条件变为 False
(使用 while
)或迭代器耗尽时(使用 for
)。
这个循环-else 结构是否源自另一种语言(无论是理论上的还是实际实现的)?它是否已被采用任何较新的语言?
也许我应该问前者,但他肯定太忙了,无暇进行这种徒劳的询问。 ;-)
相关讨论和示例:
在 for 循环中使用“else”的 Pythonic 方法
Python loop statements may have an else
clause which is executed if and only if the loop is not terminated by a break
. In other words, when the condition becomes False
(with while
) or when the iterator is exhausted (with for
).
Does this loop-else construct originate from another language (either theoretical or actually implemented)? Has it been taken up in any newer language?
Maybe I should ask the former of Guido, but surely he is too busy for such a futile inquiry. ;-)
Related discussion and examples:
Pythonic ways to use ‘else’ in a for loop
发布评论
评论(2)
Common Lisp 的 LOOP 宏中也有类似的功能, :
例如,在链接问题中找到的 Python 示例的一部分:
可能看起来像这样:
另一个观察:
Common Lisp 的条件系统也很独特。有一次,有人问它来自哪里,并被指出Kent Pitman 的论文,他说是从 Maclisp 那里得到的。同样,Common Lisp 看起来怪异的 FORMAT 函数显然来自 Multics,通过 丹·温雷布。
共同点是,语言特征往往不会遵循最能激发该语言灵感的祖先语言,而是被喜爱它们的个人带到他们正在开发的任何新语言中。因此,如果您想找出 Python 的
for
-else
的实际来源,我会查找添加它的人,并查看他们在此之前使用的语言。A similar feature is found in Common Lisp's LOOP macro, described here by Peter Seibel:
For example, part of a Python sample found in the linked question:
might look something like this:
Another observation:
Common Lisp's condition system is also unique. Someone, once, asked where it came from and was pointed to Kent Pitman's paper, where he says got it from Maclisp. Similarly, Common Lisp's weird-looking FORMAT function apparently came from Multics via Dan Weinreb.
The common thread is that language features don't tend to follow from the ancestor language that most inspired this language, but are taken by individuals who loved them to whatever new language they're working on. So if you want to find out the actual source of Python's
for
-else
, I'd look for who added it, and see what language they worked on prior to that.我刚刚在这个更普遍的问题的评论中发现了一个很好的线索。用户 ΤΖΩΤΖIΟΥ 写道:
Sinclair QL 用户指南的 OCR 版本 恰好是漂浮在互联网上。上面写着:
一个有趣的例子如下:
因此,在不同的(并且可以说不那么令人不安的)语法下,它的语义完全相同。
维基百科告诉我们,Sinclair QL 于 1984 年 2 月推出,作为 Sinclair ZX Spectrum 的后继产品,但未能取得商业成功。
I just came across a pretty good lead buried in the comments of this far more general question. User ΤΖΩΤΖΙΟΥ wrote:
An OCR rendition of Sinclair QL User Guide happens to float on the internet. It reads:
A fascinating example follows:
So, under a different (and arguably less disturbing) syntax, it's exactly the same semantics.
Wikipedia tells us that the Sinclair QL launched in February 1984 as the successor to the Sinclair ZX Spectrum, but failed to achieve commercial success.