切换视频源:

continue & break

作者: Huanyu Mao 编辑: 莫烦 2016-11-03

跳出循环

True and False ,当输入1时,a=False时,会执行接下来的语句后再跳出这个循环。

a=True
while a:
    b= input('type somesthing')
    if b=='1':
        a= False
    else:
        pass
print ('finish run')

''''
type somesthing:2
still in while
type somesthing:3
still in while
type somesthing:1
still in while    #会执行下面的语句再跳出
finish run
''''

break

break用法,在循环语句中,使用 break, 当符合跳出条件时,会直接结束循环,这是 breakTrue False 的区别。

while True:
    b= input('type somesthing:')
    if b=='1':
        break
    else:
        pass
    print('still in while')
print ('finish run')

"""
type somesthing:4
still in while
type somesthing:5
still in while
type somesthing:1
finish run
"""

continue

在代码中,满足b=1的条件时,因为使用了 continue , python 不会执行 else 后面的代码,而会直接进入下一次循环。

while True:
    b=input('input somesthing:')
    if b=='1':
       continue
    else:
        pass
    print('still in while' )

print ('finish run')
"""
input somesthing:3
still in while
input somesthing:1  # 没有"still in while"。直接进入下一次循环
input somesthing:4
still in while
input somesthing:
"""

分享到: Facebook 微博 微信 Twitter
如果你觉得这篇文章或视频对你的学习很有帮助, 请你也分享它, 让它能再次帮助到更多的需要学习的人. 莫烦没有正式的经济来源, 如果你也想支持 莫烦Python 并看到更好的教学内容, 赞助他一点点, 作为鼓励他继续开源的动力.

支持 让教学变得更优秀