Python札记呆鸟的Python数据分析

Python札记15_break、continue、else

2019-06-24  本文已影响0人  皮皮大

break:在某个地方中断循环,跳出循环体
continue:从当前位置(continue所在位置)中跳到循环体最后一行的后面,不执行最后一行。对于一个循环体来说,最后一行的后面就是开始。通过例子来体会两种语句
else:主要适合if或者while等进行联合使用。

a = 6
while a :    # a=6就表示为True,下同
    if a % 2 == 0:
        break    # 满足条件,跳出循环体,直接执行第二个print语句
    else:
        print("{} is odd number".format(a))
        a -= 1
print("{} is even number".format(a))
a = 7
while a :
    if a % 2 == 0:
        break    # 不满足条件,执行else语句,打印print,同时a减1变成6;再执行循环,满足if条件,跳出循环执行第二个print
    else:
        print("{} is odd number".format(a))
        a -= 1
print("{} is even number".format(a))
image.png
a = 9
while a:
    if a % 2 == 0:
        a -= 1
        continue
    else:
        print("{} is odd number".format(a))
        a -= 1
image.png

理解结果:


while...else...

count = 0
while count < 5:
    print("{} is less than 5 ".format(count))
    count += 1
else:
    print("{} is not less than 5 ".format(count))

按照步骤来理解

上一篇 下一篇

猜你喜欢

热点阅读