python条件语句多条件

From the previous tutorials in this series, you now have quite a bit of Python code under your belt. Everything you have seen so far has consisted of sequential execution, in which statements are always performed one after the next, in exactly the order specified.

从本系列的先前教程中,您现在掌握了很多Python代码。 到目前为止,您所看到的所有内容都包含顺序执行 ,其中语句始终按照指定的顺序在下一个之后执行。

But the world is often more complicated than that. Frequently, a program needs to skip over some statements, execute a series of statements repetitively, or choose between alternate sets of statements to execute.

但是世界往往比这更复杂。 通常,程序需要跳过某些语句,重复执行一系列语句,或者在要执行的备用语句集之间进行选择。

That is where control structures come in. A control structure directs the order of execution of the statements in a program (referred to as the program’s control flow).

这就是控制结构的用武之地。控制结构指示程序中语句的执行顺序(称为程序的控制流 )。

Here’s what you’ll learn in this tutorial: You’ll encounter your first Python control structure, the if statement.

这是在本教程中学习的内容:您将遇到第一个Python控件结构if语句。

In the real world, we commonly must evaluate information around us and then choose one course of action or another based on what we observe:

在现实世界中,我们通常必须评估我们周围的信息,然后根据我们观察到的情况选择一种行动方案或另一种行动方案:

If the weather is nice, then I’ll mow the lawn. (It’s implied that if the weather isn’t nice, then I won’t mow the lawn.)

如果天气晴朗,那我去修剪草坪。 (这意味着如果天气不好,那我就不会割草坪了。)

In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or group of statements based on the value of an expression.

在Python程序中, if语句是您执行这种决策的方式。 它允许基于表达式的值有条件地执行一个语句或一组语句。

The outline of this tutorial is as follows:

本教程的概述如下:

  • First, you’ll get a quick overview of the if statement in its simplest form.
  • Next, using the if statement as a model, you’ll see why control structures require some mechanism for grouping statements together into compound statements or blocks. You’ll learn how this is done in Python.
  • Lastly, you’ll tie it all together and learn how to write complex decision-making code.
  • 首先,您将以最简单的形式快速了解if语句。
  • 接下来,使用if语句作为模型,您将了解为什么控制结构需要某种机制来将语句分组为复合语句 。 您将学习如何在Python中完成此操作。
  • 最后,将它们结合在一起,并学习如何编写复杂的决策代码。

Ready? Here we go!

准备? 开始了!

if语句简介 (Introduction to the if Statement)

We’ll start by looking at the most basic type of if statement. In its simplest form, it looks like this:

我们将从查看最基本的if语句类型开始。 最简单的形式如下:

 if if << exprexpr >> :
    :
    << statementstatement >
>

In the form shown above:

在上面显示的形式中:

  • <expr> is an expression evaluated in Boolean context, as discussed in the section on Logical Operators in the Operators and Expressions in Python tutorial.
  • <statement> is a valid Python statement, which must be indented. (You will see why very soon.)
  • <expr>是在布尔上下文中评估的表达式,如Python运算符和表达式中有关逻辑运算符的部分所述。
  • <statement>是有效的Python语句,必须缩进。 (您很快就会明白为什么。)

If <expr> is true (evaluates to a value that is “truthy”), then <statement> is executed. If <expr> is false, then <statement> is skipped over and not executed.

如果<expr>为true(评估为“ true”的值),则执行<statement> 。 如果<expr>为false,则将跳过<statement>并且不执行。

Note that the colon (:) following <expr> is required. Some programming languages require <expr> to be enclosed in parentheses, but Python does not.

注意,冒号( : )以下<expr>是必需的。 某些编程语言要求将<expr>括在括号中,而Python则不需要。

Here are several examples of this type of if statement:

以下是这种类型的if语句的几个示例:

Note: If you are trying these examples interactively in a REPL session, you’ll find that, when you hit Enter after typing in the print('yes') statement, nothing happens.

注意:如果您在REPL会话中以交互方式尝试这些示例,则会发现,在输入print('yes')语句后按Enter时,什么都不会发生。

Because this is a multiline statement, you need to hit Enter a second time to tell the interpreter that you’re finished with it. This extra newline is not necessary in code executed from a script file.

由于这是多行语句,因此您需要再次按Enter键以告诉解释器您已完成该语句。 从脚本文件执行的代码中不需要多余的换行符。

分组语句:缩进和块 (Grouping Statements: Indentation and Blocks)

So far, so good.

到目前为止,一切都很好。

But let’s say you want to evaluate a condition and then do more than one thing if it is true:

但是,假设您要评估一个条件,然后在满足条件的情况下做不止一件事情:

If the weather is nice, then I will:

如果天气晴朗,我将:

  • Mow the lawn
  • Weed the garden
  • Take the dog for a walk
  • 修剪草坪
  • 在花园里除草
  • 带着狗散步

In all the examples shown above, each if <expr>: has been followed by only a single <statement>. There needs to be some way to say “If <expr> is true, do all of the following things.”

在上面显示的所有示例中,每个if <expr>:之后仅是一个<statement> 。 必须有某种方式说“如果<expr>为true,请执行以下所有操作。”

The usual approach taken by most programming languages is to define a syntactic device that groups multiple statements into one compound statement or block. A block is regarded syntactically as a single entity. When it is the target of an if statement, and <expr> is true, then all the statements in the block are executed. If <expr> is false, then none of them are.

大多数编程语言采用的通常方法是定义一种语法设备,该设备将多个语句分组为一个复合语句 。 块在语法上被视为单个实体。 如果它是if语句的目标并且<expr>为true,则将执行块中的所有语句。 如果<expr>为false,则都不是。

Virtually all programming languages provide the capability to define blocks, but they don’t all provide it in the same way. Let’s see how Python does it.

几乎所有的编程语言都提供了定义块的功能,但它们并非都以相同的方式提供。 让我们看看Python是如何做到的。

Python:与缩进有关 (Python: It’s All About the Indentation)

Python follows a convention known as the off-side rule, a term coined by British computer scientist Peter J. Landin. (The term is taken from the offside law in association football.) Languages that adhere to the off-side rule define blocks by indentation. Python is one of a relatively small set of off-side rule languages.

Python遵循称为越位规则的惯例,该惯例是英国计算机科学家Peter J. Landin创造的。 (该术语取自协会足球比赛的越位法。)遵守越位规则的语言通过缩进来定义块。 Python是相对较小的越位规则语言中的一种 。

Recall from the previous tutorial on Python program structure that indentation has special significance in a Python program. Now you know why: indentation is used to define compound statements or blocks. In a Python program, contiguous statements that are indented to the same level are considered to be part of the same block.

回顾先前有关Python程序结构的教程, 缩进在Python程序中具有特殊的意义 。 现在您知道原因了:缩进用于定义复合语句或块。 在Python程序中,缩进相同级别的连续语句被视为同一块的一部分。

Thus, a compound if statement in Python looks like this:

因此,Python中的复合if语句如下所示:

 if if << exprexpr >> :
    :
    << statementstatement >
    >
    << statementstatement >
    >
    ...
    ...
    << statementstatement >
>
<< following_statementfollowing_statement >
>

Here, all the statements at the matching indentation level (lines 2 to 5) are considered part of the same block. The entire block is executed if <expr> is true, or skipped over if <expr> is false. Either way, execution proceeds with <following_statement> (line 6) afterward.

在此,所有匹配缩进级别的语句(第2至5行)都被视为同一块的一部分。 整个块执行如果<expr>为真,或跳过如果<expr>是假的。 无论哪种方式,执行都会在<following_statement> (第6行)之后进行。

Python Compound if Statement
Python复合if语句

Notice that there is no token that denotes the end of the block. Rather, the end of the block is indicated by a line that is indented less than the lines of the block itself.

注意,没有标记表示该块的结尾。 相反,该块的末端由缩进的线表示,该缩进线比该块本身的线小。

Note: In the Python documentation, a group of statements defined by indentation is often referred to as a suite. This tutorial series uses the terms block and suite interchangeably.

注意:在Python文档中,由缩进定义的一组语句通常称为suite 。 本教程系列互换使用术语块和套件。

Consider this script file foo.py:

考虑此脚本文件foo.py

Running foo.py produces this output:

运行foo.py会产生以下输出:

 C:UsersjohnDocuments>python foo.py
C:UsersjohnDocuments> python foo.py
After conditional
After conditional

The four print() statements on lines 2 to 5 are indented to the same level as one another. They constitute the block that would be executed if the condition were true. But it is false, so all the statements in the block are skipped. After the end of the compound if statement has been reached (whether the statements in the block on lines 2 to 5 are executed or not), execution proceeds to the first statement having a lesser indentation level: the print() statement on line 6.

第2至5行的四个print()语句缩进到彼此相同的级别。 它们构成条件为真时将执行的块。 但这是错误的,因此将跳过该块中的所有语句。 在到达复合if语句的末尾之后(无论是否执行第2至5行的块中的语句),执行将继续执行缩进级别较低的第一个语句:第6行的print()语句。

Blocks can be nested to arbitrary depth. Each indent defines a new block, and each outdent ends the preceding block. The resulting structure is straightforward, consistent, and intuitive.

块可以嵌套到任意深度。 每个缩进定义一个新块,每个缩进结束前一个块。 最终的结构是简单,一致和直观的。

Here is a more complicated script file called blocks.py:

这是一个更复杂的脚本文件,称为blocks.py

The output generated when this script is run is shown below:

运行此脚本时生成的输出如下所示:

 C:UsersjohnDocuments>python blocks.py
C:UsersjohnDocuments> python blocks.py
Outer condition is true
Outer condition is true
Between inner conditions
Between inner conditions
Inner condition 2
Inner condition 2
End of outer condition
End of outer condition
After outer condition
After outer condition

Note: In case you have been wondering, the off-side rule is the reason for the necessity of the extra newline when entering multiline statements in a REPL session. The interpreter otherwise has no way to know that the last statement of the block has been entered.

注意:如果您一直想知道,越位规则是在REPL会话中输入多行语句时需要额外的换行符的原因。 否则,解释器无法知道已输入该块的最后一条语句。

其他语言做什么? (What Do Other Languages Do?)

Perhaps you’re wondering what the alternatives are. How are blocks defined in languages that don’t adhere to the off-side rule?

也许您想知道替代方案是什么。 如何用不遵守越位规则的语言来定义块?

The tactic used by most programming languages is to designate special tokens that mark the start and end of a block. For example, in Perl blocks are defined with pairs of curly braces ({}) like this:

大多数编程语言使用的策略是指定特殊标记,以标记块的开始和结束。 例如,在Perl中,用成对的花括号( {} )定义块,如下所示:

C/C++, Java, and a whole host of other languages use curly braces in this way.

C / C ++,Java和许多其他语言都以这种方式使用花括号。

Compound if Statement in C/C++, Perl, and Java
复合C / C ++,Perl和Java中的if语句

Other languages, such as Algol and Pascal, use keywords begin and end to enclose blocks.

其他语言,例如Algol和Pascal,则使用关键字beginend来封闭块。

哪个更好? (Which Is Better?)

Better is in the eye of the beholder. On the whole, programmers tend to feel rather strongly about how they do things. Debate about the merits of the off-side rule can run pretty hot.

在情人眼中更好。 总体而言,程序员对他们的工作方式倾向于有相当强烈的感觉。 关于越位规则的优点的辩论可能非常热门。

On the plus side:

从积极的一面:

  • Python’s use of indentation is clean, concise, and consistent.
  • In programming languages that do not use the off-side rule, indentation of code is completely independent of block definition and code function. It’s possible to write code that is indented in a manner that does not actually match how the code executes, thus creating a mistaken impression when a person just glances at it. This sort of mistake is virtually impossible to make in Python.
  • Use of indentation to define blocks forces you to maintain code formatting standards you probably should be using anyway.
  • Python对缩进的使用是干净,简洁和一致的。
  • 在不使用越位规则的编程语言中,代码的缩进完全独立于块定义和代码功能。 可能以实际上与代码的执行方式不匹配的方式编写缩进的代码,从而在一个人瞥了一眼时会产生错误的印象。 在Python中几乎不可能犯这种错误。
  • 使用缩进来定义块会迫使您保持您可能应该使用的代码格式标准。

On the negative side:

不利的一面:

  • Many programmers don’t like to be forced to do things a certain way. They tend to have strong opinions about what looks good and what doesn’t, and they don’t like to be shoehorned into a specific choice.
  • Some editors insert a mix of space and tab characters to the left of indented lines, which makes it difficult for the Python interpreter to determine indentation levels. On the other hand, it is frequently possible to configure editors not to do this. It generally isn’t considered desirable to have a mix of tabs and spaces in source code anyhow, no matter the language.
  • 许多程序员不喜欢被迫以某种方式做事。 他们往往对什么看起来好和什么不好有很强的意见,并且他们不喜欢被人屈服于特定的选择。
  • 一些编辑器在缩进行的左边插入空格和制表符的混合,这使得Python解释器很难确定缩进级别。 另一方面,通常可以配置编辑器不执行此操作。 无论哪种语言,通常都不会在源代码中混用制表符和空格。

Like it or not, if you’re programming in Python, you’re stuck with the off-side rule. All control structures in Python use it, as you will see in several future tutorials.

不管喜欢与否,如果您使用Python进行编程,则必须遵守越位规则。 如您将在以后的一些教程中看到的那样,Python中的所有控件结构都使用它。

For what it’s worth, many programmers who have been used to languages with more traditional means of block definition have initially recoiled at Python’s way but have gotten comfortable with it and have even grown to prefer it.

值得一提的是,许多已经习惯了使用更传统的块定义方式的语言的程序员最初都以Python的方式退缩,但是对此感到自在,甚至变得更喜欢它。

elseelif子句 (The else and elif Clauses)

Now you know how to use an if statement to conditionally execute a single statement or a block of several statements. It’s time to find out what else you can do.

现在您知道了如何使用if语句有条件地执行单个语句或多个语句的块。 现在是时候找出您还能做些什么了。

Sometimes, you want to evaluate a condition and take one path if it is true but specify an alternative path if it is not. This is accomplished with an else clause:

有时,您希望评估条件并采用一条路径(如果为真),但指定另一条路径(如果不是)。 这是通过else子句完成的:

 if if << exprexpr >> :
    :
    << statementstatement (( ss )) >
>
elseelse :
    :
    << statementstatement (( ss )) >
>

If <expr> is true, the first suite is executed, and the second is skipped. If <expr> is false, the first suite is skipped and the second is executed. Either way, execution then resumes after the second suite. Both suites are defined by indentation, as described above.

如果<expr>为true,则执行第一个套件,然后跳过第二个套件。 如果<expr>为false,则跳过第一个套件,然后执行第二个套件。 无论哪种方式,执行都将在第二套程序之后恢复。 如上所述,两个套件都由缩进定义。

In this example, x is less than 50, so the first suite (lines 4 to 5) are executed, and the second suite (lines 7 to 8) are skipped:

在此示例中, x小于50 ,因此将执行第一个套件(第4至5行),而跳过第二个套件(第7至8行):

Here, on the other hand, x is greater than 50, so the first suite is passed over, and the second suite executed:

另一方面, x大于50 ,因此第一个套件被传递,第二个套件被执行:

 >>> >>>  x x = = 120
120
>>>
>>>
>>> >>>  if if x x < < 5050 :
:
...     ...     printprint (( '(first suite)''(first suite)' )
)
...     ...     printprint (( 'x is small''x is small' )
)
... ...  elseelse :
:
...     ...     printprint (( '(second suite)''(second suite)' )
)
...     ...     printprint (( 'x is large''x is large' )
)
...
...
(second suite)
(second suite)
x is large
x is large

There is also syntax for branching execution based on several alternatives. For this, use one or more elif (short for else if) clauses. Python evaluates each <expr> in turn and executes the suite corresponding to the first that is true. If none of the expressions are true, and an else clause is specified, then its suite is executed:

还有基于多种选择的分支执行语法。 为此,请使用一个或多个elif (if缩写)。 Python依次评估每个<expr>并执行与第一个为true相对应的套件。 如果所有表达式都不为真,并且指定了else子句,则执行其套件:

An arbitrary number of elif clauses can be specified. The else clause is optional. If it is present, there can be only one, and it must be specified last:

可以指定任意数量的elif子句。 else子句是可选的。 如果存在,则只能有一个,并且必须最后指定:

 >>> >>>  name name = = 'Joe'
'Joe'
>>> >>>  if if name name == == 'Fred''Fred' :
:
...     ...     printprint (( 'Hello Fred''Hello Fred' )
)
... ...  elif elif name name == == 'Xander''Xander' :
:
...     ...     printprint (( 'Hello Xander''Hello Xander' )
)
... ...  elif elif name name == == 'Joe''Joe' :
:
...     ...     printprint (( 'Hello Joe''Hello Joe' )
)
... ...  elif elif name name == == 'Arnold''Arnold' :
:
...     ...     printprint (( 'Hello Arnold''Hello Arnold' )
)
... ...  elseelse :
:
...     ...     printprint (( "I don't know who you are!""I don't know who you are!" )
)
...
...
Hello Joe
Hello Joe

At most, one of the code blocks specified will be executed. If an else clause isn’t included, and all the conditions are false, then none of the blocks will be executed.

最多将执行指定的代码块之一。 如果不包括else子句,并且所有条件均为false,则不会执行任何块。

Note: Using a lengthy if/elif/else series can be a little inelegant, especially when the actions are simple statements like print(). In many cases, there may be a more Pythonic way to accomplish the same thing.

注意:使用冗长的if / elif / else系列可能有点不雅观,尤其是当操作是诸如print()类的简单语句时。 在许多情况下,可能会有更多的Python方式完成同一件事。

Here’s one possible alternative to the example above using the dict.get() method:

这是使用dict.get()方法的上述示例的一种可能替代方法:

Recall from the tutorial on Python dictionaries that the dict.get() method searches a dictionary for the specified key and returns the associated value if it is found, or the given default value if it isn’t.

从Python词典的教程中回想起dict.get()方法在字典中搜索指定的键,如果找到该键,则返回关联的值;如果找不到,则返回给定的默认值。

An if statement with elif clauses uses short-circuit evaluation, analogous to what you saw with the and and or operators. Once one of the expressions is found to be true and its block is executed, none of the remaining expressions are tested. This is demonstrated below:

带有elif子句的if语句使用短路求值,类似于您在andor运算符中看到的内容。 一旦发现其中一个表达式为真并执行了其块,则不会测试其余任何表达式。 如下所示:

 >>> >>>  var  var  # Not defined
# Not defined
Traceback (most recent call last):
  File Traceback (most recent call last):
  File "<pyshell#58>", line "<pyshell#58>" , line 1, in 1 , in <module>
    <module>
    var
var
NameError: NameError : name 'var' is not defined

name 'var' is not defined

>>> >>>  if if 'a' 'a' in in 'bar''bar' :
:
...     ...     printprint (( 'foo''foo' )
)
... ...  elif elif 11 // 00 :
:
...     ...     printprint (( "This won't happen""This won't happen" )
)
... ...  elif elif varvar :
:
...     ...     printprint (( "This won't either""This won't either" )
)
...
...
foo
foo

The second expression contains a division by zero, and the third references an undefined variable var. Either would raise an error, but neither is evaluated because the first condition specified is true.

第二个表达式包含零除,第三个表达式引用未定义的变量var 。 这两种情况都会引发错误,但是由于指定的第一个条件为true,因此不会进行评估。

单行if语句 (One-Line if Statements)

It is customary to write if <expr> on one line and <statement> indented on the following line like this:

通常在一行上写if <expr>并在下一行写<statement>缩进,如下所示:

But it is permissible to write an entire if statement on one line. The following is functionally equivalent to the example above:

但是允许在一行上编写整个if语句。 以下在功能上等同于上面的示例:

 if if << exprexpr >> : : << statementstatement >
>

There can even be more than one <statement> on the same line, separated by semicolons:

在同一行上甚至可以有多个<statement> ,用分号分隔:

But what does this mean? There are two possible interpretations:

但是,这是什么意思? 有两种可能的解释:

  1. If <expr> is true, execute <statement_1>.

    Then, execute <statement_2> ... <statement_n> unconditionally, irrespective of whether <expr> is true or not.

  2. If <expr> is true, execute all of <statement_1> ... <statement_n>. Otherwise, don’t execute any of them.

  1. 如果<expr>为true,则执行<statement_1>

    然后,无论<expr>是否为真,都无条件执行<statement_2> ... <statement_n>

  2. 如果<expr>为true,则执行所有<statement_1> ... <statement_n> 。 否则,请勿执行任何一个。

Python takes the latter interpretation. The semicolon separating the <statements> has higher precedence than the colon following <expr>—in computer lingo, the semicolon is said to bind more tightly than the colon. Thus, the <statements> are treated as a suite, and either all of them are executed, or none of them are:

Python采用后一种解释。 分隔<statements>的分号比<expr>之后的冒号具有更高的优先级-在计算机术语中,分号比冒号更紧密地绑定。 因此, <statements>被视为一个套件,并且要么全部执行,要么都不执行:

 >>> >>>  if if 'f' 'f' in in 'foo''foo' : : printprint (( '1''1' ); ); printprint (( '2''2' ); ); printprint (( '3''3' )
)
...
...
1
1
2
2
3
3
>>> >>>  if if 'z' 'z' in in 'foo''foo' : : printprint (( '1''1' ); ); printprint (( '2''2' ); ); printprint (( '3''3' )
)
...
...

Multiple statements may be specified on the same line as an elif or else clause as well:

也可以在与elifelse子句相同的行上指定多个语句:

While all of this works, and the interpreter allows it, it is generally discouraged on the grounds that it leads to poor readability, particularly for complex if statements. PEP 8 specifically recommends against it.

尽管所有这些工作都有效,并且解释器允许这样做,但通常不建议这样做,因为它会导致可读性差,尤其是对于复杂的if语句。 PEP 8特别建议不要这样做 。

As usual, it is somewhat a matter of taste. Most people would find the following more visually appealing and easier to understand at first glance than the example above:

像往常一样,这有点有点品味。 与上面的示例相比,大多数人会发现以下内容在视觉上更具吸引力并且乍一看更容易理解:

 >>> >>>  x x = = 3
3
>>> >>>  if if x x == == 11 :
:
...     ...     printprint (( 'foo''foo' )
)
...     ...     printprint (( 'bar''bar' )
)
...     ...     printprint (( 'baz''baz' )
)
... ...  elif elif x x == == 22 :
:
...     ...     printprint (( 'qux''qux' )
)
...     ...     printprint (( 'quux''quux' )
)
... ...  elseelse :
:
...     ...     printprint (( 'corge''corge' )
)
...     ...     printprint (( 'grault''grault' )
)
...
...
corge
corge
grault
grault

If an if statement is simple enough, though, putting it all on one line may be reasonable. Something like this probably wouldn’t raise anyone’s hackles too much:

但是,如果if语句足够简单,则将其全部放在一行上可能是合理的。 这样的事情可能不会引起太多人的抱怨:

条件表达式 (Conditional Expressions)

Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.) Conditional expressions were proposed for addition to the language in PEP 308 and green-lighted by Guido in 2005.

Python支持一个附加的决策实体,称为条件表达式。 (在Python文档中的各个地方,它也被称为条件运算符或三元运算符。)有人在PEP 308中提出了条件表达式,以补充该语言,并在2005年被Guido批准。

In its simplest form, the syntax of the conditional expression is as follows:

以最简单的形式,条件表达式的语法如下:

 << expr1expr1 > > if if << conditional_exprconditional_expr > > else else << expr2expr2 >
>

This is different from the if statement forms listed above because it is not a control structure that directs the flow of program execution. It acts more like an operator that defines an expression. In the above example, <conditional_expr> is evaluated first. If it is true, the expression evaluates to <expr1>. If it is false, the expression evaluates to <expr2>.

这与上面列出的if语句形式不同,因为它不是控制程序执行流程的控制结构。 它的行为更像是定义表达式的运算符。 在上面的示例中,首先评估<conditional_expr> 。 如果为true,则表达式的结果为<expr1> 。 如果为假,则表达式的结果为<expr2>

Notice the non-obvious order: the middle expression is evaluated first, and based on that result, one of the expressions on the ends is returned. Here are some examples that will hopefully help clarify:

注意非显而易见的顺序:首先对中间表达式求值,然后根据该结果返回末端的一个表达式。 以下是一些希望有助于澄清的示例:

Note: Python’s conditional expression is similar to the <conditional_expr> ? <expr1> : <expr2> syntax used by many other languages—C, Perl and Java to name a few. In fact, the ?: operator is commonly called the ternary operator in those languages, which is probably the reason Python’s conditional expression is sometimes referred to as a ternary operator.

注意: Python的条件表达式类似于<conditional_expr> ? <expr1> : <expr2> <conditional_expr> ? <expr1> : <expr2>语法被许多其他语言使用-C,Perl和Java仅举几例。 实际上, ?:运算符在这些语言中通常称为三元运算符,这可能是Python条件表达式有时被称为三元运算符的原因。

You can see in PEP 308 that the <conditional_expr> ? <expr1> : <expr2> syntax was considered for Python but ultimately rejected in favor of the syntax shown above.

您可以在PEP 308中看到<conditional_expr> ? <expr1> : <expr2> <conditional_expr> ? <expr1> : <expr2>语法在Python中已被考虑,但最终由于上面显示的语法而被拒绝。

A common use of the conditional expression is to select variable assignment. For example, suppose you want to find the larger of two numbers. Of course, there is a built-in function max() that does just this (and more) that you could use. But suppose you want to write your own code from scratch.

条件表达式的常见用法是选择变量分配。 例如,假设您要查找两个数字中较大的一个。 当然,有一个内置函数max()可以做到这一点(以及更多)。 但是假设您想从头开始编写自己的代码。

You could use a standard if statement with an else clause:

您可以使用带有else子句的标准if语句:

 >>> >>>  if if a a > > bb :
:
...     ...     m m = = a
a
... ...  elseelse :
:
...     ...     m m = = b
b
...
...

But a conditional expression is shorter and arguably more readable as well:

但是条件表达式更短,并且更具可读性:

Remember that the conditional expression behaves like an expression syntactically. It can be used as part of a longer expression. The conditional expression has lower precedence than virtually all the other operators, so parentheses are needed to group it by itself.

请记住,条件表达式在句法上的行为类似于表达式。 它可以用作较长表达式的一部分。 条件表达式的优先级实际上比所有其他运算符的优先级都低,因此需要使用括号将其自身分组。

In the following example, the + operator binds more tightly than the conditional expression, so 1 + x and y + 2 are evaluated first, followed by the conditional expression. The parentheses in the second case are unnecessary and do not change the result:

在下面的示例中, +运算符比条件表达式的绑定更紧密,因此首先计算1 + xy + 2 ,然后是条件表达式。 第二种情况下的括号是不必要的,不会改变结果:

 >>> >>>  x x = = y y = = 40

40

>>> >>>  z z = = 1 1 + + x x if if x x > > y y else else y y + + 2
2
>>> >>>  z
z
42

42

>>> >>>  z z = = (( 1 1 + + xx ) ) if if x x > > y y else else (( y y + + 22 )
)
>>> >>>  z
z
42
42

If you want the conditional expression to be evaluated first, you need to surround it with grouping parentheses. In the next example, (x if x > y else y) is evaluated first. The result is y, which is 40, so z is assigned 1 + 40 + 2 = 43:

如果要先对条件表达式求值,则需要用分组括号将其括起来。 在下一个示例中,首先评估(x if x > y else y)(x if x > y else y) 。 结果是y ,即40 ,因此z分配为1 + 40 + 2 = 43

If you are using a conditional expression as part of a larger expression, it probably is a good idea to use grouping parentheses for clarification even if they are not needed.

如果将条件表达式用作较大表达式的一部分,那么即使不需要分组括号也可能是个好主意。

Conditional expressions also use short-circuit evaluation like compound logical expressions. Portions of a conditional expression are not evaluated if they don’t need to be.

条件表达式还使用短路评估,例如复合逻辑表达式。 如果不需要,则不评估条件表达式的部分。

In the expression <expr1> if <conditional_expr> else <expr2>:

在表达式<expr1> if <conditional_expr> else <expr2>

  • If <conditional_expr> is true, <expr1> is returned and <expr2> is not evaluated.
  • If <conditional_expr> is false, <expr2> is returned and <expr1> is not evaluated.
  • 如果<conditional_expr>为true,则返回<expr1> ,并且不评估<expr2>
  • 如果<conditional_expr>为假, <expr2>返回并<expr1>不评估。

As before, you can verify this by using terms that would raise an error:

和以前一样,您可以使用会引发错误的术语来验证这一点:

 >>> >>>  'foo' 'foo' if if True True else else 11 // 0
0
'foo'
'foo'
>>> >>>  11 // 0 0 if if False False else else 'bar'
'bar'
'bar'
'bar'

In both cases, the 1/0 terms are not evaluated, so no exception is raised.

在这两种情况下,都不会评估1/0项,因此不会引发任何异常。

Conditional expressions can also be chained together, as a sort of alternative if/elif/else structure, as shown here:

条件表达式也可以链接在一起,作为if / elif / else结构的一种替代方案,如下所示:

It’s not clear that this has any significant advantage over the corresponding if/elif/else statement, but it is syntactically correct Python.

尚不清楚它相对于相应的if / elif / else语句if具有任何显着优势,但是在语法上是正确的Python。

pass声明 (The pass Statement)

Occasionally, you may find that you want to write what is called a code stub: a placeholder for where you will eventually put a block of code that you haven’t implemented yet.

有时,您可能会发现您想编写所谓的代码存根:占位符,用于在该位置最终放置尚未实现的代码块。

In languages where token delimiters are used to define blocks, like the curly braces in Perl and C, empty delimiters can be used to define a code stub. For example, the following is legitimate Perl or C code:

在使用令牌定界符来定义块的语言中(例如Perl和C中的花括号),可以使用空的定界符来定义代码存根。 例如,以下是合法的Perl或C代码:

# This is not Python
if (x)
{
}
# This is not Python
if (x)
{
}

Here, the empty curly braces define an empty block. Perl or C will evaluate the expression x, and then even if it is true, quietly do nothing.

在这里,空花括号定义了一个空块。 Perl或C将对表达式x求值,然后即使它为true,也不要执行任何操作。

Because Python uses indentation instead of delimiters, it is not possible to specify an empty block. If you introduce an if statement with if <expr>:, something has to come after it, either on the same line or indented on the following line.

由于Python使用缩进而不是定界符,因此无法指定空块。 如果使用if <expr>:引入if语句, if <expr>:必须在其后加上一行,或者在下一行缩进。

Consider this script foo.py:

考虑以下脚本foo.py

If you try to run foo.py, you’ll get this:

如果尝试运行foo.py ,则会得到以下信息:

 C:UsersjohnDocumentsPythondoc>python foo.py
C:UsersjohnDocumentsPythondoc> python foo.py
  File "foo.py", line 3
  File "foo.py", line 3
    print('foo')
    print('foo')
        ^
        ^
IndentationError: expected an indented block
IndentationError: expected an indented block

The pass statement solves this problem in Python. It doesn’t change program behavior at all. It is used as a placeholder to keep the interpreter happy in any situation where a statement is syntactically required, but you don’t really want to do anything:

pass语句解决了Python中的此问题。 它根本不会改变程序的行为。 在语法上需要语句的任何情况下,它都用作占位符,以使解释器满意,但您实际上并不想做任何事情:

Now foo.py runs without error:

现在foo.py可以foo.py运行:

 C:UsersjohnDocumentsPythondoc>python foo.py
C:UsersjohnDocumentsPythondoc> python foo.py
foo
foo

结论 (Conclusion)

With the completion of this tutorial, you are beginning to write Python code that goes beyond simple sequential execution:

完成本教程后,您将开始编写超越简单顺序执行的Python代码:

  • You were introduced to the concept of control structures. These are compound statements that alter program control flow—the order of execution of program statements.
  • You learned how to group individual statements together into a block or suite.
  • You encountered your first control structure, the if statement, which makes it possible to conditionally execute a statement or block based on evaluation of program data.
  • 向您介绍了控制结构的概念。 这些是可更改程序控制流 (程序语句的执行顺序)的复合语句。
  • 您学习了如何将单个语句组合到一个套件中
  • 您遇到了第一个控制结构if语句,它使得可以根据程序数据的评估有条件地执行一个语句或块。

All of these concepts are crucial to developing more complex Python code.

所有这些概念对于开发更复杂的Python代码都是至关重要的。

The next two tutorials will present two new control structures: the while statement and the for statement. These structures facilitate iteration, execution of a statement or block of statements repeatedly.

接下来的两个教程将介绍两个新的控件结构: while语句和for语句。 这些结构便于重复执行, 重复执行语句或语句块。

翻译自: https://www.pybloggers/2018/09/conditional-statements-in-python/

python条件语句多条件

更多推荐

python条件语句多条件_Python中的条件语句