16 循环语句
1.while 语句的格式:“while 条件 :”
while True : #循环输出"你好,世界"
print ("你好,世界")
content=1 #通过循环,让content每次循环+2
while True :
print (content)
content = content +2
while True : #无效赋值
content=1
print (content)
content = content +2
2.while 语句的终止
count =1
while count<=10 : #通过循环,输出1、2、3...10
print (count)
count = count +1
#通过循环,输出1、2、3、4、5、6、8、9、10
count = 1 #第一种办法:分开编写,先写1-6,后写8-10,尽量不要使用
while count <=6:
print (count)
count = count +1
count = 8
while count <=10:
print (count)
count = count +1
count = 1 #第二种办法,使用If语句
while count <= 10 :
if count != 7:
print (count)
count = count +1
count = 1 #第三种办法,相比第一种,稍微麻烦一点
while count <= 10 :
if count == 7:
pass #pass 直接过的意思
else :
print (count)
count = count +1
count = 1
while count <=10 and count !=7 : #and是同时满足,所以遇到7终止
print (count)
count = count +1
#结果输出1-6
3.断点
4.关键字 :break (终止)
while True :
print (666)
break #终止当前循环
print ("结束")
#练习题:通过break实现1~10
count = 1
while True:
print (count)
if count == 10:
break # 如果遇到10,就跳出当前循环
count = count +1
print ("结束")
while语句的嵌套
while True :
print ("您好")
while True :
print (666)
# 结果输出:您好 666 666 ...一直输出666
while True :
print ("您好")
while True :
print (666)
break # break只能跳出当前循环,不是跳出所有循环
#结果输出:一直循环您好 666
while True :
print ("您好")
while True :
print (666)
break
break
#结果输出:您好 666
-
关键字:continue (继续)
count = 1 while count <= 10: print (count) continue #本次循环如果遇到contiune,则不在继续往下走,而是回到条件位置重新判断 count = count + 1 #结果输出:一直是1 count = 1 while count <= 10: if count == 7: continue print (count) count = count + 1 #结果输出:输出1-6,但是程序不终止 count = 1 while count <= 10: if count == 7: count = count +1 continue print (count) count = count + 1 #结果输出:输出1-6,8-10
-
while else
count = 1 while count <10: print (count) count = count +1 else : #不满足while后的条件时触发 print ("您好") print ("结束") #结果输出:1-9 您好 结束 count = 1 while True: print (count) if count == 10: break count = count +1 else : #不满足while后的条件时触发,或条件等于False时触发,通过一定的方法跳过条件判断时,不在启动else print ("您好") print ("结束") # 结果输出:1-9 结束
-
标签:count,666,基础,content,while,课程,ptyhon,print,True From: https://www.cnblogs.com/linzaidehouhuayuan/p/17172412.html