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

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

    The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the for clause, it would never be jumped over, and so the equivalent logic would have to be provided by putting it in an if. This has been said before, but not quite in these words, so it may help somebody else. Try running the following code fragment. I'm wholeheartedly in favour of the 'no break' comment for clarity.

    for a in range(3):
        print(a)
        if a==4: # change value to force break or not
            break
    else: #no break  +10 for whoever thought of this decoration
        print('for completed OK')
    
    print('statement after for loop')
    
    0 讨论(0)
  • 2020-11-21 07:28

    I read it like "When the iterable is exhausted completely, and the execution is about to proceed to the next statement after finishing the for, the else clause will be executed." Thus, when the iteration is broken by break, this will not be executed.

    0 讨论(0)
  • 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.

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

    Here's another idiomatic use case besides searching. Let's say you wanted to wait for a condition to be true, e.g. a port to be open on a remote server, along with some timeout. Then you could utilize a while...else construct like so:

    import socket
    import time
    
    sock = socket.socket()
    timeout = time.time() + 15
    while time.time() < timeout:
        if sock.connect_ex(('127.0.0.1', 80)) is 0:
            print('Port is open now!')
            break
        print('Still waiting...')
    else:
        raise TimeoutError()
    
    0 讨论(0)
  • 2020-11-21 07:29

    I consider the structure as for (if) A else B, and for(if)-else is a special if-else, roughly. It may help to understand else.

    A and B is executed at most once, which is the same as if-else structure.

    for(if) can be considered as a special if, which does a loop to try to meet the if condition. Once the if condition is met, A and break; Else, B.

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

    To make it simple, you can think of it like that;

    • If it encounters the break command in the for loop, the else part will not be called.
    • If it does not encounter the break command in the for loop, the else part will be called.

    In other words, if for loop iteration is not "broken" with break, the else part will be called.

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