码迷,mamicode.com
首页 > 其他好文 > 详细

7.2 while 循环简介

时间:2017-12-09 19:22:56      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:循环   number   其他   something   tps   ctr   字典   测试   何事   

for 循环用于针对集合中的每个元素都一个代码块,而while 循环不断地运行,直到指定的条件不满足为止。

7.2.1 使用while 循环

技术分享图片

7.2.2 让用户选择何时退出

技术分享图片

7.2.3 使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志

可让程序在标志 为True 时继续运行,并在任何事件导致标志的值为False 时让程序停止运行

在while 语句中就只需检查一个条件——标志的当前值是否为True ,并将所有测试(是 否发生了应将标志设置为False 的事件)都放在其他地方,从而让程序变得更为整洁,标志命名为(可给它指定任何名称)

技术分享图片

技术分享图片

7.2.4 使用break 退出循环

,可使用break 语句来退出遍历列表或字典的for 循环

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter ‘quit‘ to end the program. "

while True: #以while True 打头的循环将不断运行,直到遇到break 语句
    city=input(prompt)
    if city==quit:
        break
    else:
        print("I‘d love to go to " + city.title() + "!")
        

结果

Tell me something, and I will repeat it back to you:
Enter quit to end the program. sarch
Id love to go to Sarch!

Tell me something, and I will repeat it back to you:
Enter quit to end the program. quit
>>> 

7.2.5 在循环中使用continue

current_number = 0
while current_number < 10:
    current_number += 1   #们以步长1的方式往上数
    if current_number % 2 == 0: #求模运算为0,继续返回while
        continue
    print(current_number)     
1
3
5
7
9
>>> 

技术分享图片

7.2.6 避免无限循环

 如果程序陷入无限循环,可按Ctrl+ C,也可关闭显示程序输出的终端窗口。

7.2 while 循环简介

标签:循环   number   其他   something   tps   ctr   字典   测试   何事   

原文地址:http://www.cnblogs.com/jdy113/p/8012250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!