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

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

    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()
    

提交回复
热议问题