两个最简单的例子了解Python循环语句中的break与continue

Python小白,每次都是用到小工具的时候,临时抱佛脚,各种网上抄袭,很多东西也都是记不住,看了后就忘记了,真到用到的时候又要去百度,今天偶尔看到python的基础部分的循环语句中的break和continue的用法,

看了别人的讲解还是似懂非懂,于是也尝试用了几个例子,发现这两个例子一眼就能看到具体结果,留此做个笔记,以备下次再次忘记。

正常循环1:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

vartang = 10
while vartang > 0 :
    print("vartang is %s ......" % vartang )
    vartang = vartang - 1

print("-----------------------")
 

正常输出结果1:

vartang is 10 ......
vartang is 9 ......
vartang is 8 ......
vartang is 7 ......
vartang is 6 ......
vartang is 5 ......
vartang is 4 ......
vartang is 3 ......
vartang is 2 ......
vartang is 1 ......
-----------------------

*****************************纠结的分割线*************************************

break跳出循环2:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

vartang = 10
while vartang > 0 :
    print("vartang is %s ......" % vartang )
    vartang = vartang - 1
    if vartang ==6:
        break

print("-----------------------")

break跳出循环输出结果2:

vartang is 10 ......
vartang is 9 ......
vartang is 8 ......
vartang is 7 ......
-----------------------

直接跳出循环,不再继续执行循环。

 

*****************************纠结的分割线*************************************

 

continue继续跳出循环3:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

vartang = 10
while vartang > 0 :
    print("vartang is %s ......" % vartang )
    vartang = vartang - 1
    if vartang ==6:
        continue

print("-----------------------")

continue继续跳出循环输出结果3:

vartang is 10 ......
vartang is 9 ......
vartang is 8 ......
vartang is 7 ......
vartang is 6 ......
vartang is 5 ......
vartang is 4 ......
vartang is 3 ......
vartang is 2 ......
vartang is 1 ......
-----------------------

发现上述这个循环貌似看不出什么效果......一脸蒙了,然后试图再下边加了一句,这下才看懂了:

continue继续跳出循环4:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

vartang = 10
while vartang > 0 :
    print("vartang is %s ......" % vartang )
    vartang = vartang - 1
    if vartang ==6:
        continue
    print("vartang2222 is %s ......" % vartang )

 

continue继续跳出循环输出结果4::

vartang is 10 ......
vartang2222 is 9 ......
vartang is 9 ......
vartang2222 is 8 ......
vartang is 8 ......
vartang2222 is 7 ......
vartang is 7 ......
vartang is 6 ......                 (这里明显跳出了以下步骤输出重新循环)
vartang2222 is 5 ......
vartang is 5 ......
vartang2222 is 4 ......
vartang is 4 ......
vartang2222 is 3 ......
vartang is 3 ......
vartang2222 is 2 ......
vartang is 2 ......
vartang2222 is 1 ......
vartang is 1 ......
vartang2222 is 0 ......
-----------------------

经过上述的简单的输出两个实例,我已经明白了具体的流程,具体的流程图,就不画了,觉得这种例子输出毕竟明朗,大神直接忽略,年龄大了,记性差,记录在此只是为了防止以后再次忘记,记不得这种循环路数。。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐