Skip to Content
《学习 Python》第 5 版
book

《学习 Python》第 5 版

by Mark Lutz
May 2025
Intermediate to advanced
1648 pages
23h 5m
Chinese
O'Reilly Media, Inc.
Content preview from 《学习 Python》第 5 版

第 13 章 while 和 for 循环

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

本章通过介绍 Python 语言的两个主要循环结构语句来结束我们对 Python 过程语句的学习。第一个循环语句是while 语句,它提供了一种编码一般循环的方法。第二个语句,for 语句,是为步进序列或其它可迭代对象中的项目并为每个项目运行代码块而设计的。

我们已经非正式地看过这两个语句,但我们将在这里补充更多的使用细节。同时,我们还将学习一些在循环中使用的不太显眼的语句,如breakcontinue ,并介绍一些与循环共同使用的内置语句,如range,zipmap

尽管这里涉及的whilefor 语句是为重复操作编码提供的主要语法,但在 Python 中还有其他的循环操作和概念。因此,迭代的故事将在下一章中继续,我们将在那里探索 Python 的迭代协议(for 循环使用) 和list 解析(for 循环的近亲) 的相关思想。后面的章节将探讨更奇特的迭代工具,如生成器filterreduce 。不过,现在我们还是先把事情简单化。

while 循环

Python 的while 语句是语言中最通用的迭代结构。简单地说,它重复执行一个语句块(通常是缩进的),只要顶端的测试值一直为真。 它之所以被称为 "循环",是因为控制权一直循环到语句的起始位置,直到测试值为假。当测试结果为假时,控制权就会转移到while 块后面的语句。这样做的净效果是,当顶部的测试为真时,循环的主体被重复执行。如果测试一开始就是假的,那么正文就不会运行,while 语句也会被跳过。

一般格式

在最复杂的形式中,while语句由包含测试表达式的标题行、由一个或多个正常缩进语句组成的主体,以及一个可选的else 部分组成,该部分在控制退出循环而没有遇到break 语句时执行。Python 一直在顶层评估测试并执行嵌套在循环体中的语句,直到测试返回一个 false 值:

while test:                     # Loop test
    statements                  # Loop body
else:                           # Optional else
    statements                  # Run if didn't exit loop with break

实例

为了说明这一点,让我们看看几个简单的while循环的运行情况。第一个循环由嵌套在while 循环中的print 语句组成,它只是永远打印一条信息。记得True 只是整数1 的自定义版本,并且总是代表布尔真值;因为测试总是为真,所以 Python 会永远执行正文,或者直到您停止执行它。这种行为通常被称为无限循环--它并不是真正的不朽,但您可能需要 Ctrl-C 组合键来强行终止它:

>>> while True:
...    print('Type Ctrl-C to stop me!')

下一个示例会不断切掉字符串的第一个字符,直到字符串为空,因此为假。典型的做法是直接测试对象,而不是使用更冗长的等价方法 (while x != '':)。在本章稍后部分,我们将看到使用for 循环更轻松地遍历字符串项的其他方法。

>>> x = 'spam'
>>> while x:                  # While x is not empty
...     print(x, end=' ')     # In 2.X use print x,
...     x = x[1:]             # Strip first character off x
...
spam pam am m

注意这里使用的 ...

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

学习 Java,第 6 版

学习 Java,第 6 版

Marc Loy, Patrick Niemeyer, Daniel Leuck
《高性能 Python》第二版

《高性能 Python》第二版

Micha Gorelick, Ian Ozsvald

Publisher Resources

ISBN: 9798341656963