day04_05 流程控制之while循环

"""
语法
while 条件:
代码1
代码2
代码3
"""

基本使用
一、使用while循环输出1-5
count = 0
while count < 5:
    count += 1
    print(count)

二、死循环,永远也不结束

while 1:
    1+1

不信你查看你cpu使用情况,建议多运行几个文件试试,233~~~~

三、结束while循环的两种方式break:直接终止本层循环,不会有下一次循环

i = 0
while 1:
    print('start')
    i += 1
    break
    print('end')

 

2、条件改为假:不会直接终止本层循环,会在下一次循环时终止

tag = True
while tag:
    print('start...')
    tag = False
    print('end...')

 

 

3、while+continue:终止本次循环,直接进入下一次
使用while循环输出1,2,3,5
tag = 0
while tag < 5:
    tag += 1
    if tag == 4:
        continue
    print(tag)

 4、while+else

i = 0
while i < 5:
    if i == 3:
        # i+=1
        # continue
        break
    print(i)
    i+=1
else:
    print('xxxxxxxxxxxxxxxx')
 

原文地址:https://www.cnblogs.com/HuaR-/p/14545514.html