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

前端 未结 21 2398
爱一瞬间的悲伤
爱一瞬间的悲伤 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:32

    Great answers are:

    • this which explain the history, and
    • this gives the right citation to ease yours translation/understanding.

    My note here comes from what Donald Knuth once said (sorry can't find reference) that there is a construct where while-else is indistinguishable from if-else, namely (in Python):

    x = 2
    while x > 3:
        print("foo")
        break
    else:
        print("boo")
    

    has the same flow (excluding low level differences) as:

    x = 2
    if x > 3:
        print("foo")
    else:
        print("boo")
    

    The point is that if-else can be considered as syntactic sugar for while-else which has implicit break at the end of its if block. The opposite implication, that while loop is extension to if, is more common (it's just repeated/looped conditional check), because if is often taught before while. However that isn't true because that would mean else block in while-else would be executed each time when condition is false.

    To ease your understanding think of it that way:

    Without break, return, etc., loop ends only when condition is no longer true and in such case else block will also execute once. In case of Python for you must consider C-style for loops (with conditions) or translate them to while.

    Another note:

    Premature break, return, etc. inside loop makes impossible for condition to become false because execution jumped out of the loop while condition was true and it would never come back to check it again.

提交回复
热议问题