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

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

    The else keyword can be confusing here, and as many people have pointed out, something like nobreak, notbreak is more appropriate.

    In order to understand for ... else ... logically, compare it with try...except...else, not if...else..., most of python programmers are familiar with the following code:

    try:
        do_something()
    except:
        print("Error happened.") # The try block threw an exception
    else:
        print("Everything is find.") # The try block does things just find.
    

    Similarly, think of break as a special kind of Exception:

    for x in iterable:
        do_something(x)
    except break:
        pass # Implied by Python's loop semantics
    else:
        print('no break encountered')  # No break statement was encountered
    

    The difference is python implies except break and you can not write it out, so it becomes:

    for x in iterable:
        do_something(x)
    else:
        print('no break encountered')  # No break statement was encountered
    

    Yes, I know this comparison can be difficult and tiresome, but it does clarify the confusion.

提交回复
热议问题