Why does python use 'else' after for and while loops?

前端 未结 21 1904
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 06:57

I understand how this construct works:

for i in range(10):
    print(i)

    if i == 9:
        print(\"Too big - I\'m         


        
相关标签:
21条回答
  • 2020-11-21 07:41

    There's an excellent presentation by Raymond Hettinger, titled Transforming Code into Beautiful, Idiomatic Python, in which he briefly addresses the history of the for ... else construct. The relevant section is "Distinguishing multiple exit points in loops" starting at 15:50 and continuing for about three minutes. Here are the high points:

    • The for ... else construct was devised by Donald Knuth as a replacement for certain GOTO use cases;
    • Reusing the else keyword made sense because "it's what Knuth used, and people knew, at that time, all [for statements] had embedded an if and GOTO underneath, and they expected the else;"
    • In hindsight, it should have been called "no break" (or possibly "nobreak"), and then it wouldn't be confusing.*

    So, if the question is, "Why don't they change this keyword?" then Cat Plus Plus probably gave the most accurate answer – at this point, it would be too destructive to existing code to be practical. But if the question you're really asking is why else was reused in the first place, well, apparently it seemed like a good idea at the time.

    Personally, I like the compromise of commenting # no break in-line wherever the else could be mistaken, at a glance, as belonging inside the loop. It's reasonably clear and concise. This option gets a brief mention in the summary that Bjorn linked at the end of his answer:

    For completeness, I should mention that with a slight change in syntax, programmers who want this syntax can have it right now:

    for item in sequence:
        process(item)
    else:  # no break
        suite
    

    * Bonus quote from that part of the video: "Just like if we called lambda makefunction, nobody would ask, 'What does lambda do?'"

    0 讨论(0)
  • 2020-11-21 07:41

    I read it something like:

    If still on the conditions to run the loop, do stuff, else do something else.

    0 讨论(0)
  • 2020-11-21 07:45

    I think documentation has a great explanation of else, continue

    [...] it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement."

    Source: Python 2 docs: Tutorial on control flow

    0 讨论(0)
提交回复
热议问题