1、循环的语法与基本使用
while 条件:
代码1
代码2
代码3
count=0
while count <5:
print(count)
count+=1
print('顶级代码')
2、死循环与效率问题
while True:
name=input("请输入银行密码:")
print(name)
纯计算IO的死循环导致致命的效率问题
while 1:
name=input("请输入银行密码:")
print(name)
3、循环的应用
#username = 'dls'
#paasword = '123'
#两个问题:
#重复代码问题
输对了应该不用重复
'''while True:
inp_name=input('请输入您的账号:')
inp_pwd=input('请输入您的密码:')
if inp_name == username and inp_pwd == paasword:
print("登录成功")
else:
print("登录失败")'''
4、退出循环的两种方式
方式一:将条件改成False,等到下次循环判断条件时才会生效
'''username = 'dls'
paasword = '123'
tag = True
while tag:
inp_name=input('请输入您的账号:')
inp_pwd=input('请输入您的密码:')
if inp_name == username and inp_pwd == paasword:
print("登录成功")
tag = False
else:
print("登录失败")
print('=======end===')
'''
方式二:break,只要运行到break就会立刻终止
# username = 'dls'
# paasword = '123'
# while True:
# inp_name=input('请输入您的账号:')
# inp_pwd=input('请输入您的密码:')
# if inp_name == username and inp_pwd == paasword:
# print("登录成功")
# break
# else:
# print("登录失败")
# print('=======end===')
5、条件
6、while +break
‘’’
伪代码
每一层都必须配一个break(使用break循环嵌套每层都要加退出)
while True:
while True:
while True:
break
break
break
使用变量的方式一下就可以退出多层
tag=True
while tag:
while tag:
while tag:
tag =False
‘’’
7、while循环嵌套
# break 方式
# username = 'dls'
# paasword = '123'
# while True:
# inp_name=input('请输入您的账号:')
# inp_pwd=input('请输入您的密码:')
# if inp_name == username and inp_pwd == paasword:
# print("登录成功")
# while True:
# cmd=input('请输入命令:')
# if cmd == 'q':
# break
# print('命令{x}正在运行'.format(x=cmd))
# break
# else:
# print("登录失败")
# 改变条件的方式
# username = 'dls'
# paasword = '123'
# tag = True
# while tag:
# inp_name=input('请输入您的账号:')
# inp_pwd=input('请输入您的密码:')
# if inp_name == username and inp_pwd == paasword:
# print("登录成功")
# while tag:
# cmd=input('请输入命令:')
# if cmd == 'q':
# tag = False
# else:
# print('命令{x}正在运行'.format(x=cmd))
# tag = False
# else:
# print("登录失败")
8、while +continue:结束本次循环,直接进入下一次循环
在continue之后添加代码毫无意义,永远不会运行
# count=0
# while count <6:
# if count ==4:
# count+=1
# continue
# print(count)
# count+=1
9、while +else
while True:
if …:
else:
print(‘else包含的代码在while循环结束后,并且是在没有break打断的情况下,才会运行’)
count=0
# while count <6:
# count+=1
# print(count)
# continue
# else:
# print('倒计时同意')
# username = 'dls'
# paasword = '123'
# count = 0
# while count < 3:
# inp_name = input('请输入您的账号:')
# inp_pwd = input('请输入您的密码:')
# if inp_name == username and inp_pwd == paasword:
# ...
# print('输入正确退出')
# break
# else:
# print('账号或密码错误')
# count += 1
# else:
# print('错误退出')