doy05循环语法学习笔记

时间:2021-12-22 12:58:26

doy05循环语法学习笔记

一、while循环语法:

1.基本用法示例
x = 1
while x <= 5:
print(x)
x += 1
2.死循环:永远不结束的循环
如:while True: #永远为真的情况为死循环
print(1)
如:while True:
print(1)
如:while True: # IO
name = input(">> ")
print(name)
3.结束while循环有两种方式
方法一:把条件改为False,必须要等到下一次循环判断条件是才能结束循环
x = 1
meng = True
while meng:
if x == 5: # x相等于5时
meng = False #执行
print(x)
x += 1
方式二:break终止本层循环,会立即结束while循环,根本没有下一次
x = 1
meng = True
while meng:
if x == 5:
break
print(x)
x += 1

while语法案例

案例1:
方式一:用值为False来结束循环
meng = True
while meng:
a = input('请输入您的账号:')
b = input('请输入您的密码:')
if a == "me" and b == "123":
print('登录成功')
meng = False # 用值为False
else:
print('登录失败')
方式二:利用break结束了这一层循环
while True:
a = input('请输入您的账号:')
b = input('请输入您的密码:')
if a == 'meng' and b == '123':
print('登录成功')
break
else:
print('登录失败')
案例2:
x = 0
meng =True
while True:
a = input('请输入你的账号:')
b = input('请输入你的密码:')
if a == 'me' and b == '123':
print('登录成功')
break
else:
print('登录失败')
x += 1
if x == 3:
print("您输入次数已经超过三次,请等30分钟后再输入")
break
4.while+continue:contincoue终止本次进入下一次
x = 1
while x <= 5:
if x ==3:
x += 1
continue
print(x)
x += 1
5.while用列表取值
a = ['name_men', 'age_18', 'height_175']
i = 0
while i < 3:
print(a[i])
i += 1

for循环

一、for更擅于遍厉值,for循环的次数取决值的个数

for循环语法:取值循环
for 变量名 in 可迭代对象: #可迭代对象可以是:字典、列表、字符串、元组、集合
for a in ['name_meng','age_18','height_175']: #for循环次数取决于后面包含几个值
print(a)
代码1:
x = [121,222,333,444,555]
i = 0
while i < len(x):
print(x[i])
i += 1
代码2:
dic = {'k1':'meng','k2':'11','k3':'male'}
for k in dic:
print(k,dic[k])
代码3:
dic = [['k1','meng'],['k2','11'],['k3','male']]
for x,y in dic: # x,y = ['k1','meng']
print(x,y)

二、for+break

x = 0
while x < 3:
inp_name = input('请输入您的账号:')
inp_pwd = input('请输入您的密码:')
if inp_name == 'meng' and inp_pwd == '123':
print('登录成功')
while True:
cmd = input('>')
if cmd == 'quit':
break
print('reu <%s>' %(cmd))
break
else:
print('登录失败')
x += 1

三、for循环控制循环次数:range(顾头不顾尾)

for i in range(3):
inp_name = input('请输入您的账号:')
inp_pwd = input('请输入您的密码:')
if inp_name == 'meng' and inp_pwd == '123':
print('登录成功')
while True:
cmd = input('>')
if cmd == 'quit':
break
print('reu <%s>' % cmd)
break
else:
print('登录失败')
else:
print('输入次数过多')

四、for+continue

for x in range(6): # 0 1 2 3 5
if x == 4: #跳过打印4
continue
print(x)