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 版

第 12 章 if 测试和语法规则

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

本章介绍 Pythonif语句,它是根据测试结果从备选操作中进行选择的主要语句。因为这是我们第一次深入了解,复合语句--嵌入其他语句的语句--我们还将在这里比第 10 章的介绍更详细地探讨 Python 语句语法模型背后的一般概念。由于if 语句引入了测试的概念,本章还将处理布尔表达式,介绍 "三元 "if 表达式,并补充一些真值测试的细节。

if 语句

简单地说,Pythonif 语句选择要执行的操作。它与对应的表达式一起,是 Python 的主要选择工具,代表了 Python 程序所拥有的大部分逻辑。它也是我们的第一个复合语句。像所有的复合 Python 语句一样,if 语句可以包含其他语句,包括其他ifs。事实上,Python 允许您在程序中按顺序(使它们一个接一个地执行)和任意嵌套方式(使它们只在特定条件下执行,如选择和循环)组合语句。

一般格式

Pythonif 语句是大多数过程语言中典型的if语句。它的形式是一个if 测试,然后是一个或多个可选的elif ("else if")测试和最后一个可选的else 块。测试和else 部分各有一个相关的嵌套语句块,缩进在标题行下。当运行if 语句时,Python 会执行与第一个测试相关的代码块,如果所有测试都证明为真,则执行else 代码块。if 语句的一般形式如下:

if test1:                 # if test
    statements1           # Associated block
elif test2:               # Optional elifs
    statements2
else:                     # Optional else
    statements3

基本范例

为了演示,让我们看看if 语句工作的几个简单示例。除了初始if 测试及其相关语句外,所有部分都是可选的。因此,在最简单的情况下,其他部分都可以省略:

>>> if 1:
...     print('true')
...
true

请注意,在这里使用的基本界面中交互式键入时,续行的提示符会变为... ;而在 IDLE 中,您只需下降到缩进行即可(按 Backspace 键返回)。空行(按两次 Enter 键即可得到空行)终止并运行整个语句。请记住,1 是布尔真值(稍后我们将看到,单词True 与之等价),因此该语句的测试总是成功的。要处理假结果,请编写else

>>> if not 1:
...     print('true')
... else:
...     print('false')
...
false

多路分支

下面是一个 更复杂的if语句示例,其中包含所有可选部分:

>>> x = 'killer rabbit'
>>> if x == 'roger':
...     print("shave and a haircut")
... elif x == 'bugs':
...     print("what's up doc?")
... else:
...     print('Run away! Run away!')
...
Run away! Run away!

这条多行语句从if 行一直延伸到嵌套在else 下面的代码块。运行时,Python 会执行嵌套在第一个测试为真时下面的语句,如果所有测试都为假,则执行else 部分(在本例中,所有测试都为假)。在实践中,elifelse 部分都可以省略,每个部分嵌套的语句可能不止一条。请注意,ifelifelse 这三个词是通过垂直排列和相同的缩进而联系在一起的。 ...

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