Python的while else

python中有一个其独有的功能,while else.

它的作用是判断是循环是否被终止,如果没有被终止,那么就会执行else,反之则不会执行。还是用一段代码来解释吧

 

else被执行:

count = 0
while count <= 5:
    print('loop', count)
    count += 1
else:
    print('loop is done...')

print('out of loop')

'''
loop 0
loop 1
loop 2
loop 3
loop 4
loop 5
loop is done...
out of loop
'''

 

else未被执行:

count = 0
while count <= 5:
    print('loop', count)
    if count == 3:
        break
    count += 1
else:
    print('loop is done...')

print('out of loop')

'''
loop 0
loop 1
loop 2
loop 3
loop 4
loop 5
loop is end...
out of loop
'''

 

posted @ 2018-11-02 23:26  梁少华  阅读(2902)  评论(0编辑  收藏  举报