1.why:大气,吃饭,日复一日,听音乐单曲循环、列表循环,程序循环:账户用户名密码
2.what:while无限循环
3.how:
(1)基本结构:
while 条件:
循环体
-------------------------------------------------------------------------------
while True:
print('狼的诱惑')
print('月亮之上')
print('庐州月')
print('人间')
-------------------------------------------------------------------------------
此程序死循环,一直 狼的诱惑、月亮之上、庐州月、人间、狼的诱惑、月亮之上、庐州月、人间......一直循环下去
-
-
若是True则进入循环体
-
一直执行到循环体的底部
-
返回条件处,继续判断条件,条件成立,则再进入循环体;不满足条件则推出循环
-
.......
(3)
-
flag (标志位):改变条件
#练习题:输出1~100
-------------------------------------------------------------------------------
count = 1 #方法一
wwhile count < 101:
print(count)
count = count + 1
count = 1 #方法二
flag = True
while flag:
print(count)
count = count + 1
if count == 101:
flag = False
-------------------------------------------------------------------------------
#练习题:输出1+2+3....+100的结果
-------------------------------------------------------------------------------
count = 1
add = 0
while count < 101:
add = add + count
count = count+1
print(add)
-------------------------------------------------------------------------------
-
break:循环中遇到break直接退出循环
#练习:打印1~100所有的偶数
-------------------------------------------------------------------------------
#方法一(运用break)
count = 2
while True:
print(count)
count = count + 2
if count == 102:
break
#方法二(运用%)
count = 1
while count < 101:
if count % 2 ==0:
print(count)
count = count + 1
-------------------------------------------------------------------------------
-
continue:退出本次循环,继续下一次循环
-------------------------------------------------------------------------------
flag = True
while flag:
print(111)
print(222)
flag = False
continue
print(333)
-------------------------------------------------------------------------------
此程序由上往下进行,打印 111 222 然后flag为False,遇到了continue,结束本次循环,进行下次循环,再判断条件,此时条件不满足,结束循环,所以不打印333
所以,此程序结果为111 222
-------------------------------------------------------------------------------
count = 1
while count < 5:
print (count)
if count == 2:
break
count = count + 1
else:
print (666)
-------------------------------------------------------------------------------
此程序为while else型,进入循环当满足条件count等于2时,break直接跳出循环,但是不执行else,所以结果为1 2
4.where:你需要重复之前的动作,输入用户名密码,考虑到while循环。