while循环

'''
1 while循环的基本语法
while 条件:
子代码1
子代码2
子代码3

count=0
while count < 5: # 5 < 5
print(count)
count+=1 # count=5


print('======end=====')

2、死循环:循环永远不终止,称之为死循环
count=0
while count < 5:
print(count)

3、循环的应用
需求一:输错密码,重新输入重新验证

方式一:
username='egon'
password='123'

while True:
inp_user=input('请输入你的用户名:')
inp_pwd=input('请输入你的密码:')

if inp_user == username and inp_pwd == password:
print('登录成功')
break
else:
print('输入的账号或密码错误')

print('======end======')

方式二
username='egon'
password='123'

tag=True
while tag:
inp_user=input('请输入你的用户名:')
inp_pwd=input('请输入你的密码:')

if inp_user == username and inp_pwd == password:
print('登录成功')
tag=False
else:
print('输入的账号或密码错误')

print('======end======')

4、如何终止循环
方式一:把条件改成假,必须等到下一次循环判断条件时循环才会结束
tag=True
while tag: # tag=False
print('ok')
tag=False
print('hahahahhahahahahahaha')

方式二:break,放到当前循环的循环体中,一旦运行到break则立刻终止本层循环,不会进行下一次循环的判断
while True:
print('ok')
break
print('hahahahhahahahahahaha')

嵌套多层循环,需求是想一次性终止所有层的循环,推荐使用方式二
方式一:
while 条件1:
while 条件2:
while 条件3:
break
break
break

方式二:
tag=True
while tag:
while tag:
while tag:
tag=False

5、循环嵌套小案例
需求一:输错账号密码,重新输入重新验证
需求二:输错3次,退出程序

需求三:输对账号密码,登录成功之后,可以循环接收用户输入的命令并执行

username = 'egon'
password = '123'

count = 0

while count < 3: # count=3
# if count == 3:break

inp_user = input('请输入你的用户名:')
inp_pwd = input('请输入你的密码:')

if inp_user == username and inp_pwd == password:
print('登录成功')

while True:
cmd = input('请输入你的命令(输入q退出): ')
if cmd == 'q':
break
print('%s 正在执行' % cmd)

break
else:
print('输入的账号或密码错误')
count += 1 # count=3

username = 'egon'
password = '123'

count = 0
tag=True

while tag:
if count == 3:break

inp_user = input('请输入你的用户名:')
inp_pwd = input('请输入你的密码:')

if inp_user == username and inp_pwd == password:
print('登录成功')
while tag:
cmd = input('请输入你的命令(输入q退出): ')
if cmd == 'q':
# 退出程序
tag=False
else:
print('%s 正在执行' % cmd)

else:
print('输入的账号或密码错误')
count += 1 # count=3


6、while+continue:continue会结束本次循环,直接进入下一次循环
count = 1

while count < 6: # 5 < 6
if count == 4: # 4==4
count += 1 # count=5
continue # 强调:在continue之后不应该写与其同级的代码,因为为将无法运行

print(count) #
count += 1 # 6

7、while+else
count=1
while count < 6:
# if count == 3:break
if count == 4:
count+=1
continue
print(count)
count+=1
else:
#else对应的子代码块会在while循环结束后,并且不是被break强行结束的情况下执行
print('====end====')
'''
原文地址:https://www.cnblogs.com/0B0S/p/12358256.html