Python流程控制之while循环

一、基本使用

count = 2
while count < 4:
    print(count)
    count += 1
print('顶级循环')

二、退出循环的两种方式

1、将条件改为False,下次才结束

复制代码
username = 'brynn'
userpwd = '123'
tag = True
while tag: name = input('your name :') pwd = input('your password :') if name == username and pwd == userpwd: print('success') tag=False else: print('False and input again') print('end')
复制代码

2、break,只要运行到break,就会立即终止本层循环。

复制代码
username = 'brynn'
userpwd = '123'

while 1:
    name = input('your name :')
    pwd = input('your password :')

    if name == username and pwd == userpwd:
        print('success')
        break
    else:
        print('False and input again')
    print('end')
复制代码

三、结束本次循环,直接进入下一次:while+continue

复制代码
count=0
while count<6:
    if count==4:
        count+=1
        continue
    print(count)
    count+=1
# 结果
# 0
# 1
# 2
# 3
# 5
复制代码

四、while+else

复制代码
count = 0
while count < 6:
    if count == 4:
        count += 1
        continue
    print(count)
    count += 1
else:
    print('^.^')
# 0
# 1
# 2
# 3
# 5
# ^.^
复制代码

 

posted @   Brynn626  阅读(89)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示