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

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

    Here's a way to think about it that I haven't seen anyone else mention above:

    First, remember that for-loops are basically just syntactic sugar around while-loops. For example, the loop

    for item in sequence:
        do_something(item)
    

    can be rewritten (approximately) as

    item = None
    while sequence.hasnext():
        item = sequence.next()
        do_something(item)
    

    Second, remember that while-loops are basically just repeated if-blocks! You can always read a while-loop as "if this condition is true, execute the body, then come back and check again".

    So while/else makes perfect sense: It's the exact same structure as if/else, with the added functionality of looping until the condition becomes false instead of just checking the condition once.

    And then for/else makes perfect sense too: because all for-loops are just syntactic sugar on top of while-loops, you just need to figure out what the underlying while-loop's implicit conditional is, and then the else corresponds to when that condition becomes False.

提交回复
热议问题