day05 while及for循环
01.流程控制之while循环
① 什么是循环
循环就是重复做某件事
② 为何要有循环
控制计算机能够像人一样重复做某件事
③ 循环的使用
基本语法:
While 条件:
代码1
代码2
代码3
……..
基本用法:
#打印0-10
count=0
while count <= 10:
print('loop',count)
count+=1
#打印0-10之间的偶数
count=0
while count <= 10:
if count%2 == 0:
print('loop',count)
count+=1
#打印0-10之间的奇数
count=0
while count <= 10:
if count%2 == 1:
print('loop',count)
count+=1
④ 死循环
import time
num=0
while True:
print('count',num)
time.sleep(1)
num+=1
⑤ 结束循环的两种方式
方式一: 把条件改为False
特点:等到本次循环体代码运行完毕后,下一次循环判断条件时才会生效
i=0
tag=True
while tag:
if i == 5:
tag=False
print(i)
i+=1
方式二:break代表结束本层循环
特点:立即干掉本层while循环
i=0
tag=True
while tag:
if i == 5:
tag=False
# break
print(i)
i+=1
⑥ 多层循环嵌套
方式一:
tag = True
while tag:
while tag:
while tag:
tag = False
方式二
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 == "egon" and inp_pwd == "123":
print('login successful')
# break
tag = False
else:
print('username or password error')
# print('=======================>')
案例2
while True:
inp_user = input("username>>>: ")
inp_pwd = input("password>>>: ")
if inp_user == "egon" and inp_pwd == "123":
print('login successful')
while True:
print("""
0 退出
1 取款
2 存款
3 转账
""")
choice = input("请输入您的命令编号:")
if choice == "0":
break
elif choice == "1":
print("正在取款。。。")
elif choice == "2":
print("正在存款。。。")
elif 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:
# break
count += 1
continue # continue同级别之后千万别写代码,写了也不会运行
print(count)
count += 1
案例
while True:
inp_user = input("username>>>: ")
inp_pwd = input("password>>>: ")
if inp_user == "egon" and inp_pwd == "123":
print('login successful')
break
else:
print('username or password error')
# continue # continue一定不要加在最后一步
⑧ while+else:else的子代码块会在while循环正常死亡时运行,没有被break干掉就叫正常死亡
count = 0
while count < 5:
if count == 2:
# count += 1
# continue
break
print(count)
count += 1
else:
print('====>')
02.流程控制之for循环
①.for,语法如下
for x in names:
print(x)
dic={"k1":111,'K2':2222,"k3":333}
for x in dic:
print(x,dic[x])
for x in "hello":
print(x)
for x,y in [["name","egon"],["age",18],["gender","male"]]: # x,y = ['name', 'egon']
print(x,y)
②.break与continue
for i in [11,22,33,44,55]:
if i == 33:
break
print(i)
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()
i=0
while i < 3:
print(111)
print(222)
print(333)
i+=1
for x in range(3):
print(111)
print(222)
print(333)

浙公网安备 33010602011771号