0
点赞
收藏
分享

微信扫一扫

Python控制流程之while循环

color_小浣熊 2022-01-20 阅读 22

一、while循环(条件循环)

"""
语法规则:
while 条件:
    条件成立执行的代码
else:
    条件不成立的时候,执行的代码
"""
    
i = 0
while i < 5:
    print('hello python')
    i += 1
    print('这是第{}次打印'.format(i))
else:
    print('i<5不成立,此时i的值是{}'.format(i))

执行结果:
hello python
这是第1次打印
hello python
这是第2次打印
hello python
这是第3次打印
hello python
这是第4次打印
hello python
这是第5次打印
i<5不成立,此时i的值是5

二、死循环

n = 1
while n <= 100:
    print('hello python')

运行结果:hello python
hello python
hello python
hello python
…………
注意:避免死循环的出现

三、break:终止循环,跳出循环体

# 账户密码输入正确的时候,不需要继续循环,所以需要break跳出循环
user = 'xiaoyao'
pwd = 'buding'
while True:
    username = input('请输入账户名:')
    password = input('请输入密码:')
    if user == username and pwd == password:
        print('恭喜登录成功')
        # 使用break跳出循环
        break
    else:
        print('账号或者密码错误!')
print('从循环出来了')

运行结果:
请输入账户名:xiaoyao
请输入密码:buding
恭喜登录成功
从循环出来了

四、continue:中止当前本轮循环,开启下一轮循环

# 循环去打印1-5,当其中3不用打印
n = 0
while n < 5:
    n += 1
    if n == 3:
        continue
    print(n)
    print(f'----{n}----')
print('从循环出来了')

五、while循环中的else

(1)循环条件不成立,退出循环执行else中的代码
(2)使用break跳出循环,不会执行else中的代码

举报

相关推荐

0 条评论