一、while循环:
1.语法结构:
while 条件:
代码1
代码2
else:
代码3
代码4
2.中止while循环的两种方法
①利用变量改变条件从而中止循环:
tag = True
while tag:
print("1")
tag = False
print("2") # 打印了1,2
通过以上的例子,打印了结果为1,2说明,通过变量改变条件而中止循环不是立刻中止,而是等本次循环结束后,再次进入循环判断条件时,因为条件不成立而结束了循环。
②break
tag = True
while tag:
print("1")
break
print("2") # 打印了1
通过使用break的例子我们可以知道,当代码运行到break,会立刻中止循环,不再执行后续代码。但break只能中止本层的循环,当有两层甚至三次循环嵌套的时候,就需要两个甚至三个break。所以在多次循环嵌套时,利用变量改变条件从而中止循环在一些情况下是更好的选择。
3.死循环:条件一直满足,没有在代码中设置中止手段
while True:
# print('Hello')
# input(">>: ")
1+1
当产生死循环,会操作cpu会处于不停的工作中,尤其是while循环体中的代码是数学运算而不是IO操作时。
4.while+continue: 终止本次循环,继续下一次循环
强调1:不要在continue之后编写同级别的代码
强调2:如果不想执行本次循环之后的代码,可以用continue,但是如果本次循环本来就没有要继续运行的后续代码了,就没必要加continue了
continue和break不同,continue会中止本次循环,不再执行本次continue后续代码,然后开始新的循环。
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count) # 输出1 2 4 5
即当count为3时候,print(count)并没有执行。
db_name = "yang"
db_pwd = "123"
while True:
inp_name = input("请输入您的用户名: ")
inp_pwd = input("请输入您的密码: ")
if inp_name == db_name and inp_pwd == db_pwd:
print("用户登录成功")
break
else:
print("用户账号或密码错误")
continue
此时的continue并没有意义,因为后续本来也没有代码了
5.while+else:当while循环体正常结束(只要不被break,都算正常结束)的时候,将执行else的代码
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count) # 输出1 2 4 5
else:
print("循环正常结束")
-----------------
1
2
4
5
循环正常结束
所以使用continue并不影响while+else的使用。
6.while的嵌套:在while中还可以套用while,可以使用break中止,当嵌套比较多时候,可以使用变量来控制
name = 'yang'
pwd = '123'
while True:
inp_name = input('请输入您的用户名:')
inp_pwd = input('请输入您的密码:')
if inp_name ==name and inp_pwd == pwd :
print('登录成功')
while True:
print(
"""
0 退出
1 取款
2 提现
3 转账
"""
,end='')
cmd = input("请输入您的指令:")
if cmd =='0':
break
elif cmd == '1':
print('正在取款')
elif cmd == '2':
print('正在提现')
elif cmd == '3':
print('正在转账')
else:
print('未知的指令')
break
else:
print('账号或者密码错误')
二、for循环
for循环和while循环同样是循环,不过在某些情况下,for循环更方便。
当需要循环对字典,列表,字符串进行取值的时候for循环更方便。
for循环与while循环的区别:
1.while循环的中止依赖条件变为False或者使用break
2.for循环的中止取决于所需取的值的个数或者使用break
语法结构:
for 变量 in 能存放多段数据的类型:
代码1
else:
代码2
1.基本使用
①取出列表中的值
l = [1,2,3,4,5,6]
for i in l:
print(i)
----------------------------
1
2
3
4
5
6
②取出字典中的值,此时取出的是key
dic = {'name' : 'yang','age' : 18}
for key in dic :
print(key)
------------------------
name
age
③取字符串
str1 = 'hello'
for i in str1:
print(i)
-------------------------------
h
e
l
l
o
④取嵌套列表
l = [["aaa", 1111], ["bbb", 2222], ["ccc", 3333]]
for x, y in l: # x,y=["aaa",1111]
print(x, y)
2.for + break:中止本层for循环
for x in [111,222,333,4444,555]:
if x == 333:
break
print(x)
-------------------------------
111
222
三:for + continue:中止本次循环,进行下一次循环
for i in [1,2,3,4,5]:
if i == 3:
continue
print(i)
-------------------------
1
2
4
5
四:for + else:只要for循环正常结束(不被break),就执行else
for x in [111,222,333,444,555]:
print(x)
else:
print('for循环正常结束')
------------------------------------------------
111
222
333
444
555
for循环正常结束