第 7 章 For 和 While
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
为了这个,为了那个、 我们的辛劳晦涩难懂,还有那......
罗伯特-伯恩斯,"为那而那"
用if,elif, 和else 进行测试,从上到下,一行一行地往下运行。 有时,我们需要做不止一次的事情。我们需要一个循环,Python 给了我们两个选择:while 和for 。
用 while 重复
在 Python 中,最简单的循环机制是while 。使用交互式解释器,尝试一个简单的循环,打印从 1 到 5 的数字:
>>>count=1>>>whilecount<=5:...(count)...count+=1...12345>>>
我们首先将1 的值赋值给count 。while 循环比较count和5的值,如果count 小于或等于5 ,则继续。在循环内部,我们打印count 的值,然后用语句count += 1 将其值递增1。
Python 回到循环的顶端,再次比较count 和5 。count 的值现在是2 ,所以while 循环的内容再次被执行,count 被递增到3 。
这个过程一直持续到count 从5 递增到循环底部的6 (count += 1 行)。在下一次到顶部的行程中,count 现在是6 ,所以count <= 5 现在是False ,while 循环结束。Python 继续执行下一行。
用 break 取消
如果想要循环到某件事情发生为止,但又不确定什么时候会发生,那么 可以使用一个带有break 语句的无限循环。这次,让我们通过 Python 的input() 函数从键盘上读取一行输入,然后以第一个字母大写的形式打印出来。当输入一行只包含字母q 时,我们就中断循环:
>>>whileTrue:...stuff=input("String to capitalize [type q to quit]: ")...ifstuff=="q":...break...(stuff.capitalize())...String to capitalize [type q to quit]: testTestString to capitalize [type q to quit]: hey, it worksHey, it worksString to capitalize [type q to quit]: q>>>
使用 continue 向前跳转
有时, ,您并不想跳出循环,只是出于某种原因想跳到下一次迭代。这里有一个假想的例子:让我们读取一个整数,如果是奇数,则打印它的平方,如果是偶数,则跳过它。我甚至添加了一些注释。同样,我们使用q 来停止循环:
>>>whileTrue:...value=input("Integer, please [q to quit]: ")...ifvalue=='q':# quit...break...number=int(value)...ifnumber%2==0:# an even number...continue...(number,"squared is",number*number)...Integer, please ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access