Skip to Content
Python入门指南, 3rd Edition
book

Python入门指南, 3rd Edition

by Bill Lubanovic
September 2025
Intermediate to advanced
660 pages
7h 15m
Chinese
O'Reilly Media, Inc.
Content preview from Python入门指南, 3rd Edition

第 7 章 For 和 While

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

为了这个,为了那个、 我们的辛劳晦涩难懂,还有那......

罗伯特-伯恩斯,"为那而那"

if,elif, 和else 进行测试,从上到下,一行一行地往下运行。 有时,我们需要做不止一次的事情。我们需要一个循环,Python 给了我们两个选择:whilefor

用 while 重复

在 Python 中,最简单的循环机制是while 。使用交互式解释器,尝试一个简单的循环,打印从 1 到 5 的数字:

>>> count = 1
>>> while count <= 5:
...     print(count)
...     count += 1
...
1
2
3
4
5
>>>

我们首先将1 的值赋值给countwhile 循环比较count5的值,如果count 小于或等于5 ,则继续。在循环内部,我们打印count 的值,然后用语句count += 1 将其值递增1。 Python 回到循环的顶端,再次比较count5count 的值现在是2 ,所以while 循环的内容再次被执行,count 被递增到3

这个过程一直持续到count5 递增到循环底部的6 (count += 1 行)。在下一次到顶部的行程中,count 现在是6 ,所以count <= 5 现在是Falsewhile 循环结束。Python 继续执行下一行。

用 break 取消

如果想要循环到某件事情发生为止,但又不确定什么时候会发生,那么 可以使用一个带有break 语句的无限循环。这次,让我们通过 Python 的input() 函数从键盘上读取一行输入,然后以第一个字母大写的形式打印出来。当输入一行只包含字母q 时,我们就中断循环:

>>> while True:
...     stuff = input("String to capitalize [type q to quit]: ")
...     if stuff == "q":
...         break
...     print(stuff.capitalize())
...
String to capitalize [type q to quit]: test
Test
String to capitalize [type q to quit]: hey, it works
Hey, it works
String to capitalize [type q to quit]: q
>>>

使用 continue 向前跳转

有时, ,您并不想跳出循环,只是出于某种原因想跳到下一次迭代。这里有一个假想的例子:让我们读取一个整数,如果是奇数,则打印它的平方,如果是偶数,则跳过它。我甚至添加了一些注释。同样,我们使用q 来停止循环:

>>> while True:
...     value = input("Integer, please [q to quit]: ")
...     if value == 'q':      # quit
...         break
...     number = int(value)
...     if number % 2 == 0:   # an even number
...        continue
...     print(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

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

生成式人工智能设计模式

生成式人工智能设计模式

Valliappa Lakshmanan, Hannes Hapke

Publisher Resources

ISBN: 9798341668898