day05
1、什么是循环
循环就是重复做某件事
2、为何要有循环
为了控制计算机能够像人一样去重复做某件事
3、如何用循环
基本语法:
while 条件:
代码1
代码2
代码3
一、基本用法
用法 1:
i = 0
tag = True
while tag:
if i == 5:
tag = False
print(i)
i += 1
用法 2:
i = 0
while i < 6:
print(i)
i += 1
二、死循环:条件永远为True
while True:
1 + 1
三、结束while循环的两种方法
方式1:把条件改为Falese
特点:等到本次循环体代码运行完毕后,下一次循环判断条件时才会生效
i = 0
tag = True
while tag:
if i == 5:
tag = False
print(i)
i += 1
方式2:
特点:立即跳出本层while循环
i = 0
tag = True
while tag:
if i == 5:
tag = False
方式2:
i = 0
tag = True
if i == 5:
tag = break
print(i)
i += 1
四、嵌套多层的while循环
方式1:
tag = True
while tag:
while tag:
while tag:
while tag:
tag = False
方式2:
while True:
while True:
while True:
break
break
break
案例1
tag = True
while tag:
inp_user = input("username>>>:")
inp_pwd = input("password>>>:")
if inp_user == "gwj" and inp_pwd == "123":
print('login successful')
#break or tag = False
else:
print('username or password error')
案例2:
while True:
inp_user = input("username>>>:")
inp_pwd = input("password>>>:")
if inp_user == "gwj" and inp_pwd == "123":
print("login successful")
while True:
print("""
0 退出
1 取款
2 存款
3 转账
""")
choice = input("请输入您的命令编号:")
if choice == "0"
print("已退出")
break
elfi choice == "1":
print("正在取款")
elfi choice == "2":
print("正在存款")
elfi choice == "3":
print("正在转账")
else:
print("您输入的指令不存在")
break
else:
print("username or password error")
五、while+continue:结束本次循环,直接进入下一次
count = 0
while count < 6:
if count == 2 or count == 4:
count += 1
coutinue # 同级别之后的代码不会运行
print(count)
count += 1
六:while+else:else的子代码块会在while循环正常死亡时运行,没有被break干掉就叫正常死亡
count = 0
while count < 5:
if count == 2:
# count += 1
# continue
break
print(count)
count += 1
else:
print('====>')
一、 for循环的使用
for+break
for i in [11,22,33,44,55]:
if i == 33:
break
print(i)
二、 for+continue
for i in [11,22,33,44,55]:
if i == 33:
continue
print(i)
三、for+else
for i in [11,22,33,44,55]:
if i == 33:
break
print(i)
else:
print('++++++++>')
四、range:遍历

浙公网安备 33010602011771号