博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python中的运算符和表达式
阅读量:2527 次
发布时间:2019-05-11

本文共 30820 字,大约阅读时间需要 102 分钟。

After finishing our previous tutorial on in this series, you should now have a good grasp of creating and naming Python objects of different types. Let’s do some work with them!

在完成了本系列中有关上一教程之后,您现在应该已经掌握了创建和命名不同类型的Python对象的知识。 让我们与他们合作吧!

Here’s what you’ll learn in this tutorial: You’ll see how calculations can be performed on objects in Python. By the end of this tutorial, you will be able to create complex expressions by combining objects and operators.

这是在本教程中学习的内容:您将了解如何在Python中的对象上执行计算。 在本教程结束时,您将能够通过组合对象和运算符来创建复杂的表达式

Don’t miss the follow up tutorial: and you’ll know when the next installment comes out.

不要错过后续教程: ,您将知道下一期的发行时间。

In Python, operators are special symbols that designate that some sort of computation should be performed. The values that an operator acts on are called operands.

在Python中,运算符是特殊符号,用于指定应执行某种计算。 运算符所作用的值称为操作数

Here is an example:

这是一个例子:

>>> >>>  a a = = 1010>>> >>>  b b = = 2020>>> >>>  a a + + bb3030

In this case, the + operator adds the operands a and b together. An operand can be either a literal value or a variable that references an object:

在这种情况下, +运算符将操作数ab在一起。 操作数可以是文字值或引用对象的变量:

A sequence of operands and operators, like a + b - 5, is called an expression. Python supports many operators for combining data objects into expressions. These are explored below.

一连串的操作数和运算符,例如a + b - 5 ,称为表达式。 Python支持将数据对象组合为表达式的许多运算符。 这些将在下面进行探讨。

算术运算符 (Arithmetic Operators)

The following table lists the arithmetic operators supported by Python:

下表列出了Python支持的算术运算符:

Operator 操作员 Example Meaning 含义 Result 结果
+ (unary)+ (一元) +a+a Unary Positive一元正 a
In other words, it doesn’t really do anything. It mostly exists for the sake of completeness, to complement Unary Negation.
a
换句话说,它实际上没有任何作用。 它的存在主要是为了完整性,是对一元否定的补充。
+ (binary)+ (二进制) a + ba + b Addition加成 a and abb总和
- (unary)- (一元) -a-a Unary Negation一元否定 a but opposite in signa ,但符号相反
- (binary)- (二进位) a - ba - b Subtraction减法 b subtracted from b从减去aa
** a * ba * b Multiplication乘法 a and abb乘积
// a / ba / b Division a is divided by a除以b.b
The result always has type
结果始终为float.float类型。
%% a % ba % b Modulus模量 a is divided by a除以bb余数
//// a // ba // b Floor Division (also called 地板部门 (也称为Integer Division)整数部门 a is divided by a除以b, rounded to the next smallest whole numberb ,四舍五入到下一个最小整数
**** a ** ba ** b Exponentiation求幂 a raised to the power of a提升为bb的幂

Here are some examples of these operators in use:

以下是这些使用中的运算符的一些示例:

>>> >>>  a a = = 44>>> >>>  b b = = 33>>> >>>  ++ aa44>>> >>>  -- bb-3-3>>> >>>  a a + + bb77>>> >>>  a a - - bb11>>> >>>  a a * * bb1212>>> >>>  a a / / bb1.33333333333333331.3333333333333333>>> >>>  a a % % bb11>>> >>>  a a ** ** bb6464

The result of standard division (/) is always a float, even if the dividend is evenly divisible by the divisor:

即使除数可以被除数平均除,标准除法( / )的结果始终是float

When the result of floor division (//) is positive, it is as though the fractional portion is truncated off, leaving only the integer portion. When the result is negative, the result is rounded down to the next smallest (greater negative) integer:

底数除法( // )的结果为正数时,就好像小数部分被截断了,只剩下整数部分。 当结果为负数时,结果将舍入为下一个最小(更大的负数)整数:

>>> >>>  10 10 / / 442.52.5>>> >>>  10 10 // // 4422>>> >>>  10 10 // // -- 44-3-3>>> >>>  -- 10 10 // // 44-3-3>>> >>>  -- 10 10 // // -- 4422

Note, by the way, that in a REPL session, you can display the value of an expression by just typing it in at the >>> prompt without print(), the same as you can with a literal value or variable:

注意,顺便说一下,在REPL会话中,您可以通过仅在>>>提示符下键入表达式而无需print()来显示表达式的值,这与使用文字值或变量的方法相同:

比较运算符 (Comparison Operators)

Operator 操作员 Example Meaning 含义 Result 结果
==== a == ba == b Equal to等于 True if the value of True如果值a is equal to the value of a等于的值bb
否则为False otherwiseFalse
!=!= a != ba != b Not equal to不等于 True if a不等于a is not equal to bbTrue
否则为False otherwiseFalse
<< a < ba < b Less than少于 True if a小于a is less than b则为bTrue
否则为False otherwiseFalse
<=<= a <= ba <= b Less than or equal to小于或等于 True if a小于或等于a is less than or equal to b则为bTrue
否则为False otherwiseFalse
>> a > ba > b Greater than比...更棒 True if a大于a is greater than b则为bTrue
否则为False otherwiseFalse
>=>= a >= ba >= b Greater than or equal to大于或等于 True if a大于或等于a is greater than or equal to b则为bTrue
否则为False otherwiseFalse

Here are examples of the comparison operators in use:

以下是使用中的比较运算符的示例:

>>> >>>  a a = = 1010>>> >>>  b b = = 2020>>> >>>  a a == == bbFalseFalse>>> >>>  a a != != bbTrueTrue>>> >>>  a a <= <= bbTrueTrue>>> >>>  a a >= >= bbFalseFalse>>> >>>  a a = = 3030>>> >>>  b b = = 3030>>> >>>  a a == == bbTrueTrue>>> >>>  a a <= <= bbTrueTrue>>> >>>  a a >= >= bbTrueTrue

Comparison operators are typically used in Boolean contexts like conditional and loop statements to direct program flow, as you will see later.

比较运算符通常用于条件条件和循环语句等布尔上下文中,以引导程序流,这将在后面介绍。

浮点值的相等比较 (Equality Comparison on Floating-Point Values)

Recall from the earlier discussion of that the value stored internally for a float object may not be precisely what you’d think it would be. For that reason, it is poor practice to compare floating-point values for exact equality. Consider this example:

从前面的讨论回想 ,对于内部存储值float对象可能不是正是你想象的那样。 出于这个原因,比较浮点值以获得完全相等的方法是不明智的做法。 考虑以下示例:

Yikes! The internal representations of the addition operands are not exactly equal to 1.1 and 2.2, so you cannot rely on x to compare exactly to 3.3.

kes! 加法操作数的内部表示形式不完全等于1.12.2 ,因此您不能依靠x3.3进行精确比较。

The preferred way to determine whether two floating-point values are “equal” is to compute whether they are close to one another, given some tolerance. Take a look at this example:

确定两个浮点值是否“相等”的首选方法是在给定一定公差的情况下计算两个浮点值是否彼此接近。 看一下这个例子:

>>> >>>  tolerance tolerance = = 0.000010.00001>>> >>>  x x = = 1.1 1.1 + + 2.22.2>>> >>>  absabs (( x x - - 3.33.3 ) ) < < tolerancetoleranceTrueTrue

abs() returns absolute value. If the absolute value of the difference between the two numbers is less than the specified tolerance, they are close enough to one another to be considered equal.

abs()返回绝对值。 如果两个数字之间的差的绝对值小于指定的公差,则它们彼此足够接近以被视为相等。

逻辑运算符 (Logical Operators)

The logical operators not, or, and and modify and join together expressions evaluated in Boolean context to create more complex conditions.

逻辑运算符not ,, orand修改并将在布尔上下文中评估的表达式结合在一起以创建更复杂的条件。

涉及布尔操作数的逻辑表达式 (Logical Expressions Involving Boolean Operands)

As you have seen, some objects and expressions in Python actually are of Boolean type. That is, they are equal to one of the Python objects True or False. Consider these examples:

如您所见,Python中的某些对象和表达式实际上是布尔类型的。 也就是说,它们等于Python对象TrueFalse 。 考虑以下示例:

In the examples above, x < 10, callable(x), and t are all Boolean objects or expressions.

在上面的示例中, x < 10callable(x)t都是布尔对象或表达式。

Interpretation of logical expressions involving not, or, and and is straightforward when the operands are Boolean:

当操作数为布尔值时,涉及notorand的逻辑表达式的解释很简单:

Operator 操作员 Example Meaning 含义
notnot not xnot x True if True ,如果x is xFalseFalse
如果False if xx is True则为TrueFalse
(Logically reverses the sense of
(逻辑上反转x)x的含义)
oror x or yx or y True if either True如果任一x or xy is yTrueTrue
否则为False otherwiseFalse
andand x and yx and y True if both True如果两个x and xy are yTrueTrue
否则为False otherwiseFalse

Take a look at how they work in practice below.

在下面查看它们在实践中的工作方式。

not和布尔操作数 (not and Boolean Operands)

x = 5x = 5not x < 10not x < 10FalseFalsenot callable(x)not callable(x)TrueTrue
Operand 操作数 Value Logical Expression 逻辑表达 Value
x < 10x < 10 TrueTrue not x < 10not x < 10 FalseFalse
callable(x)callable(x) FalseFalse not callable(x)not callable(x) TrueTrue

or和布尔操作数 (or and Boolean Operands)

Operand 操作数 Value Operand 操作数 Value Logical Expression 逻辑表达 Value
x < 10x < 10 TrueTrue callable(x)callable(x) FalseFalse x < 10 or callable(x)x < 10 or callable(x) TrueTrue
x < 0x < 0 FalseFalse callable(x)callable(x) FalseFalse x < 0 or callable(x)x < 0 or callable(x) FalseFalse

and和布尔操作数 (and and Boolean Operands)

x = 5x = 5x < 10 and callable(x)x < 10 and callable(x)FalseFalsex < 10 and callable(len)x < 10 and callable(len)TrueTrue
Operand 操作数 Value Operand 操作数 Value Logical Expression 逻辑表达 Value
x < 10x < 10 TrueTrue callable(x)callable(x) FalseFalse x < 10 and callable(x)x < 10 and callable(x) FalseFalse
x < 10x < 10 TrueTrue callable(len)callable(len) TrueTrue x < 10 or callable(len)x < 10 or callable(len) TrueTrue

在布尔上下文中评估非布尔值 (Evaluation of Non-Boolean Values in Boolean Context)

Many objects and expressions are not equal to True or False. Nonetheless, they may still be evaluated in Boolean context and determined to be “truthy” or “falsy.”

许多对象和表达式不等于TrueFalse 。 但是,它们仍可以在布尔上下文中进行评估,并确定为“真实”或“虚假”。

So what is true and what isn’t? As a philosophical question, that is outside the scope of this tutorial!

那么什么是真实的,什么不是? 作为一个哲学问题,这超出了本教程的范围!

But in Python, it is well-defined. All the following are considered false when evaluated in Boolean context:

但是在Python中,它是明确定义的。 在布尔上下文中进行评估时,以下所有内容均被视为错误:

  • The Boolean value False
  • Any value that is numerically zero (0, 0.0, 0.0+0.0j)
  • An empty string
  • An object of a built-in composite data type which is empty (see below)
  • The special value denoted by the Python keyword None
  • 布尔值False
  • 任何值,该值是数字零( 00.00.0+0.0j
  • 空字符串
  • 内置复合数据类型为空的对象(请参见下文)
  • Python关键字None表示的特殊值

Virtually any other object built into Python is regarded as true.

实际上,Python中内置的任何其他对象都被认为是正确的。

You can determine the “truthiness” of an object or expression with the built-in bool() function. bool() returns True if its argument is truthy and False if it is falsy.

您可以使用内置的bool()函数确定对象或表达式的“真实性”。 如果bool()的参数为True则返回True如果参数为false,则返回False

数值 (Numeric Value)

A zero value is false. A non-zero value is true.

零值为假。 非零值是true。

(String)

An empty string is false. A non-empty string is true.

空字符串为false。 非空字符串为true。

>>> >>>  printprint (( boolbool (( '''' ), ), boolbool (( """" ), ), boolbool (( """""""""""" ))))False False FalseFalse False False>>> >>>  printprint (( boolbool (( 'foo''foo' ), ), boolbool (( " "" " ), ), boolbool (( ''' '''''' ''' ))))True True TrueTrue True True

内置复合数据对象 (Built-In Composite Data Object)

Python provides built-in composite data types called list, tuple, dict, and set. These are “container” types that contain other objects. An object of one of these types is considered false if it is empty and true if it is non-empty.

Python提供了称为listtupledictset内置复合数据类型。 这些是包含其他对象的“容器”类型。 这些类型之一的对象如果为空,则视为false;如果为非空,则为true。

The examples below demonstrate this for the list type. (Lists are defined in Python with square brackets.)

下面的示例针对list类型对此进行了演示。 (列表在Python中定义,并带有方括号。)

For more information on the list, tuple, dict, and set types, see the upcoming tutorials.

有关listtupledictset类型的更多信息,请参见后续教程。

None关键字 (None Keyword)

None is always false:

None一个总是错误的:

>>> >>>  boolbool (( NoneNone ))FalseFalse

涉及非布尔操作数的逻辑表达式 (Logical Expressions Involving Non-Boolean Operands)

Non-Boolean values can also be modified and joined by not, or and, and. The result depends on the “truthiness” of the operands.

非布尔值也可以通过notorand进行修改和连接。 结果取决于操作数的“真实性”。

not和非布尔操作数 (not and Non-Boolean Operands)

Here is what happens for a non-Boolean value x:

这是非布尔值x

x isx not x isnot x
“truthy” “真” FalseFalse
“falsy” “虚假” TrueTrue

Here are some concrete examples:

以下是一些具体示例:

or和非布尔操作数 (or and Non-Boolean Operands)

This is what happens for two non-Boolean values x and y:

这是两个非布尔值xy发生的情况:

x isx x or y isx or y
truthy 真实的 xx
falsy 虚假的 yy

Note that in this case, the expression x or y does not evaluate to either True or False, but instead to one of either x or y:

请注意,在这种情况下,表达式x or y不是TrueFalse ,而是xy

>>> >>>  x x = = 33>>> >>>  y y = = 44>>> >>>  x x or or yy33>>> >>>  x x = = 0.00.0>>> >>>  y y = = 4.44.4>>> >>>  x x or or yy4.44.4

Even so, it is still the case that the expression x or y will be truthy if either x or y is truthy, and falsy if both x and y are falsy.

即便如此,仍然使表达的情况下x or y将truthy如果任一xy是truthy,和falsy如果两个xy是falsy。

and与非布尔操作数 (and and Non-Boolean Operands)

Here’s what you’ll get for two non-Boolean values x and y:

这是两个非布尔值xy

x isx x and y isx and y
“truthy” “真” yy
“falsy” “虚假” xx

As with or, the expression x and y does not evaluate to either True or False, but instead to one of either x or y. x and y will be truthy if both x and y are truthy, and falsy otherwise.

or ,表达式x and y取值不会为TrueFalse ,而是取值为xyx and y将truthy如果两个xy是truthy,和falsy否则。

复合逻辑表达式和短路评估 (Compound Logical Expressions and Short-Circuit Evaluation)

So far, you have seen expressions with only a single or or and operator and two operands:

到目前为止,您已经看到只有一个orand运算符和两个操作数的表达式:

x x or or yyx x and and yy

Multiple logical operators and operands can be strung together to form compound logical expressions.

多个逻辑运算符和操作数可以串在一起形成复合逻辑表达式。

复合or表达式 (Compound or Expressions)

Consider the following expression:

考虑以下表达式:

x1 or x2 or x3 orxn

x 1 or x 2 or x 3 orx n

This expression is true if any of the xi are true.

如果x i中的任何一个为真,则该表达式为真。

In an expression like this, Python uses a methodology called , also called McCarthy evaluation in honor of computer scientist John McCarthy. The xi operands are evaluated in order from left to right. As soon as one is found to be true, the entire expression is known to be true. At that point, Python stops and no more terms are evaluated. The value of the entire expression is that of the xi that terminated evaluation.

在这样的表达式中,Python使用了一种称为的方法,也称为McCarthy评估,以纪念计算机科学家John McCarthy。 从左到右依次评估x i操作数。 一旦发现一个表达式为真,就知道整个表达式为真。 到那时,Python停止了,不再评估任何条件。 整个表达式的值就是终止评估的x i的值。

To help demonstrate short-circuit evaluation, suppose that you have a simple “identity” function f() that behaves as follows:

为了帮助演示短路评估,假设您有一个简单的“ identity”函数f() ,其行为如下:

  • f() takes a single argument.
  • It displays the argument to the console.
  • It returns the argument passed to it as its return value.
  • f()有一个参数。
  • 它向控制台显示参数。
  • 它返回传递给它的参数作为其返回值。

(You will see how to define such a function in the upcoming tutorial on Functions.)

(您将在接下来的“函数”教程中看到如何定义这样的函数。)

Several example calls to f() are shown below:

下面显示了对f()几个示例调用:

Because f() simply returns the argument passed to it, we can make the expression f(arg) be truthy or falsy as needed by specifying a value for arg that is appropriately truthy or falsy. Additionally, f() displays its argument to the console, which visually confirms whether or not it was called.

因为f()只是返回传递给它的参数,所以我们可以通过为arg指定一个适当的真或假值来使表达式f(arg)为真或假。 此外, f()其参数显示到控制台,该控制台以可视方式确认是否已调用它。

Now, consider the following compound logical expression:

现在,考虑以下复合逻辑表达式:

>>> >>>  ff (( 00 ) ) or or ff (( FalseFalse ) ) or or ff (( 11 ) ) or or ff (( 22 ) ) or or ff (( 33 ))-> f(0) = 0-> f(0) = 0-> f(False) = False-> f(False) = False-> f(1) = 1-> f(1) = 111

The interpreter first evaluates f(0), which is 0. A numeric value of 0 is false. The expression is not true yet, so evaluation proceeds left to right. The next operand, f(False), returns False. That is also false, so evaluation continues.

解释器首先计算f(0) ,它是0 。 数值0为false。 该表达式还不正确,因此评估从左到右进行。 下一个操作数f(False)返回False 。 这也是错误的,因此评估将继续。

Next up is f(1). That evaluates to 1, which is true. At that point, the interpreter stops because it now knows the entire expression to be true. 1 is returned as the value of the expression, and the remaining operands, f(2) and f(3), are never evaluated. You can see from the display that the f(2) and f(3) calls do not occur.

接下来是f(1) 。 得出的值为1 ,这是正确的。 此时,解释器停止,因为它现在知道整个表达式为真。 返回1作为表达式的值,并且永远不会评估其余操作数f(2)f(3) 。 从屏幕上可以看到没有发生f(2)f(3)调用。

复合and表达 (Compound and Expressions)

A similar situation exists in an expression with multiple and operators:

具有多个and运算符的表达式中也存在类似的情况:

x1 and x2 and x3 andxn

x 1 and x 2 and x 3 andx n

This expression is true if all the xi are true.

如果所有x i均为真,则此表达式为真。

In this case, short-circuit evaluation dictates that the interpreter stop evaluating as soon as any operand is found to be false, because at that point the entire expression is known to be false. Once that is the case, no more operands are evaluated, and the falsy operand that terminated evaluation is returned as the value of the expression:

在这种情况下,短路评估指示一旦发现任何操作数为假,解释器就会立即停止评估,因为此时已知整个表达式为假。 在这种情况下,将不再对任何操作数求值,并且将终止求值的虚假操作数作为表达式的值返回:

In both examples above, evaluation stops at the first term that is false—f(False) in the first case, f(0.0) in the second case—and neither the f(2) nor f(3) call occurs. False and 0.0, respectively, are returned as the value of the expression.

在以上两个示例中,求值都在第一个为假的条件下停止求值,第一种情况为f(False) ,第二种情况为f(0.0) ,并且没有发生f(2)f(3)调用。 False0.0作为表达式的值。

If all the operands are truthy, they all get evaluated and the last (rightmost) one is returned as the value of the expression:

如果所有操作数均为真,则对它们全部进行求值,并返回最后一个(最右侧)作为表达式的值:

>>> >>>  ff (( 11 ) ) and and ff (( 2.22.2 ) ) and and ff (( 'bar''bar' ))-> f(1) = 1-> f(1) = 1-> f(2.2) = 2.2-> f(2.2) = 2.2-> f(bar) = bar-> f(bar) = bar'bar''bar'

利用短路评估的习语 (Idioms That Exploit Short-Circuit Evaluation)

There are some common idiomatic patterns that exploit short-circuit evaluation for conciseness of expression.

有一些常见的惯用模式,它们利用短路评估来简化表达。

避免异常 (Avoiding an Exception)

Suppose you have defined two variables a and b, and you want to know whether (b / a) > 0:

假设您已经定义了两个变量ab ,并且想知道(b / a) > 0

But you need to account for the possibility that a might be 0, in which case the interpreter will raise an exception:

但是,您需要考虑a可能为0的可能性,在这种情况下,解释器将引发异常:

>>> >>>  a a = = 00>>> >>>  b b = = 11>>> >>>  (( b b / / aa ) ) > > 00Traceback (most recent call last):  File Traceback (most recent call last):  File "
", line "
" , line 1, in 1 , in
(( b b / / aa ) ) > > 00ZeroDivisionError: ZeroDivisionError : division by zerodivision by zero

You can avoid an error with an expression like this:

您可以使用以下表达式避免错误:

When a is 0, a != 0 is false. Short-circuit evaluation ensures that evaluation stops at that point. (b / a) is not evaluated, and no error is raised.

a0a != 0为假。 短路评估可确保评估在此时停止。 (b / a)不被评估,并且不会引发错误。

If fact, you can be even more concise than that. When a is 0, the expression a by itself is falsy. There is no need for the explicit comparison a != 0:

如果事实是这样,那么您甚至可以更加简洁。 当a0 ,表达式a本身就是虚假的。 无需显式比较a != 0

>>> >>>  a a = = 00>>> >>>  b b = = 11>>> >>>  a a and and (( b b / / aa ) ) > > 0000

选择默认值 (Selecting a Default Value)

Another idiom involves selecting a default value when a specified value is zero or empty. For example, suppose you want to assign a variable s to the value contained in another variable called string. But if string is empty, you want to supply a default value.

另一个习惯用法是在指定值为零或为空时选择默认值。 例如,假设您想将变量s分配给另一个名为string变量中包含的值。 但是,如果string为空,则要提供默认值。

Here is a concise way of expressing this using short-circuit evaluation:

这是使用短路评估来表达这一点的简洁方法:

If string is non-empty, it is truthy, and the expression string or '<default_value>' will be true at that point. Evaluation stops, and the value of string is returned and assigned to s:

如果string为非空,则为true,此时表达式string or '<default_value>'将为true。 评估停止, string值返回并分配给s

>>> >>>  string string = = 'foo bar''foo bar'>>> >>>  s s = = string string or or '
''
'>>> >>> ss'foo bar''foo bar'

On the other hand, if string is an empty string, it is falsy. Evaluation of string or '<default_value>' continues to the next operand, '<default_value>', which is returned and assigned to s:

另一方面,如果string为空字符串,则为假。 string or '<default_value>'求值继续到下一个操作数'<default_value>' ,该操作数返回并分配给s

链接比较 (Chained Comparisons)

Comparison operators can be chained together to arbitrary length. For example, the following expressions are nearly equivalent:

比较运算符可以链接到任意长度。 例如,以下表达式几乎等效:

x x < < y y <= <= zzx x < < y y and and y y <= <= zz

They will both evaluate to the same Boolean value. The subtle difference between the two is that in the chained comparison x < y <= z, y is evaluated only once. The longer expression x < y and y <= z will cause y to be evaluated twice.

它们都将求值为相同的布尔值。 两者之间的细微差别在于,在链式比较x < y <= zy仅被评估一次。 较长的表达式x < y and y <= z将导致y被评估两次。

Note: In cases where y is a static value, this will not be a significant distinction. But consider these expressions:

注意:y是静态值的情况下,这不会有明显区别。 但是请考虑以下表达式:

If f() is a function that causes program data to be modified, the difference between its being called once in the first case and twice in the second case may be important.

如果f()是导致程序数据被修改的函数,则在第一种情况下调用一次和在第二种情况下调用两次之间的区别可能很重要。

More generally, if op1, op2, …, opn are comparison operators, then the following have the same Boolean value:

更一般而言,如果op 1 ,op 2 …, op n是比较运算符,则以下内容具有相同的布尔值:

x1op1 x2op2 x3 … xn-1opn xn

x 1 op 1 x 2 op 2 x 3 …x n-1 op n x n

x1op1 x2and x2op2 x3and … xn-1opn xn

x 1 op 1 x 2 and x 2 op 2 x 3 and …x n-1 op n x n

In the former case, each xi is only evaluated once. In the latter case, each will be evaluated twice except the first and last, unless short-circuit evaluation causes premature termination.

在前一种情况下,每个x i仅被评估一次。 在后一种情况下,除非第一个和最后一个评估,每个评估将两次,除非短路评估导致过早终止。

按位运算符 (Bitwise Operators)

Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. The following operators are supported:

按位运算符将操作数视为二进制数字序列,并对其进行逐位操作。 支持以下运算符:

Operator 操作员 Example Meaning 含义 Result 结果
&& a & ba & b AND AND of the bits in the corresponding position of the operands. ( 。 ( 1 if both are 1如果两者都1, otherwise 1 ,否则0.)0 )。
|| a | ba | b OR OR of the bits in the corresponding position of the operands. ( 。 ( 1 if either is 1如果任一为1, otherwise 1 ,否则0.)0 )。
~~ ~a~a negation取反 Each bit position in the result is the logical negation of the bit in the corresponding position of the operand. (1 if 0, 0 if 1.) 结果中的每个位位置是操作数对应位置中位的逻辑取反。 ( 1如果00 ,如果1 )。
^^ a ^ ba ^ b XOR (exclusive OR)XOR(异或) XOR of the bits in the corresponding position of the operands. (XOR 。 ( 1 if the bits in the operands are different, 1如果在操作数的位不同, 0 if they are the same.)0如果它们是相同的。)
>>>> a >> na >> n Shift right 向右移 n n places n places.n位。
<<<< a << na << n Shift left 向左移 n n places位置 n places.n位。

Here are some examples:

这里有些例子:

>>> >>>  '0b{:04b}''0b{:04b}' .. formatformat (( 0b1100 0b1100 & & 0b10100b1010 ))'0b1000''0b1000'>>> >>>  '0b{:04b}''0b{:04b}' .. formatformat (( 0b1100 0b1100 | | 0b10100b1010 ))'0b1110''0b1110'>>> >>>  '0b{:04b}''0b{:04b}' .. formatformat (( 0b1100 0b1100 ^ ^ 0b10100b1010 ))'0b0110''0b0110'>>> >>>  '0b{:04b}''0b{:04b}' .. formatformat (( 0b1100 0b1100 >> >> 22 ))'0b0011''0b0011'>>> >>>  '0b{:04b}''0b{:04b}' .. formatformat (( 0b0011 0b0011 << << 22 ))'0b1100''0b1100'

Note: The purpose of the '0b{:04b}'.format() is to format the numeric output of the bitwise operations, to make them easier to read. You will see the format() method in much more detail later. For now, just pay attention to the operands of the bitwise operations, and the results.

注意: '0b{:04b}'.format()是格式化按位运算的数字输出,以使其更易于阅读。 稍后您将更详细地看到format()方法。 现在,只需要注意按位运算的操作数和结果。

身份运营商 (Identity Operators)

Python provides two operators, is and is not, that determine whether the given operands have the same identity—that is, refer to the same object. This is not the same thing as equality, which means the two operands refer to objects that contain the same data but are not necessarily the same object.

Python提供了两个操作符, isis not ,用于确定给定的操作数是否具有相同的标识,即引用相同的对象。 这与相等性不同,这意味着两个操作数引用的对象包含相同的数据,但不一定是同一对象。

Here is an example of two object that are equal but not identical:

这是两个相等但不相同的对象的示例:

Here, x and y both refer to objects whose value is 1001. They are equal. But they do not reference the same object, as you can verify:

在此, xy均指值为1001对象。 他们是平等的。 但是,它们没有引用相同的对象,因此您可以验证:

>>> >>>  idid (( xx ))6030792060307920>>> >>>  idid (( yy ))6030793660307936

x and y do not have the same identity, and x is y returns False.

xy不具有相同的标识,并且x is y返回False

You saw previously that when you make an assignment like x = y, Python merely creates a second reference to the same object, and that you could confirm that fact with the id() function. You can also confirm it using the is operator:

之前您看到过,当您进行x = y这样的赋值时,Python只会创建对同一对象的第二个引用,并且您可以使用id()函数确认这一事实。 您也可以使用is运算符确认它:

In this case, since a and b reference the same object, it stands to reason that a and b would be equal as well.

在这种情况下,由于ab引用相同的对象,因此可以推论ab也将相等。

Unsurprisingly, the opposite of is is is not:

不出所料,相反isis not

>>> >>>  x x = = 1010>>> >>>  y y = = 2020>>> >>>  x x is is not not yyTrueTrue

运算符优先级 (Operator Precedence)

Consider this expression:

考虑以下表达式:

There is ambiguity here. Should Python perform the addition 20 + 4 first and then multiply the sum by 10? Or should the multiplication 4 * 10 be performed first, and the addition of 20 second?

这里有歧义。 Python是否应该先执行20 + 4的加法运算,然后将总和乘以10 ? 还是应该先执行4 * 10乘法,然后执行20加法?

Clearly, since the result is 60, Python has chosen the latter; if it had chosen the former, the result would be 240. This is standard algebraic procedure, found universally in virtually all programming languages.

显然,由于结果为60 ,Python选择了后者; 如果选择前者,则结果为240 。 这是标准的代数过程,几乎在所有编程语言中都可以找到。

All operators that the language supports are assigned a precedence. In an expression, all operators of highest precedence are performed first. Once those results are obtained, operators of the next highest precedence are performed. So it continues, until the expression is fully evaluated. Any operators of equal precedence are performed in left-to-right order.

语言支持的所有运算符都被分配一个优先级。 在表达式中,所有优先级最高的运算符将首先执行。 一旦获得这些结果,就执行下一个最高优先级的运算符。 因此,它将继续进行直到表达式被完全求值。 任何具有相同优先级的运算符都按从左到右的顺序执行。

Here is the order of precedence of the Python operators you have seen so far, from lowest to highest:

到目前为止,这是您所看到的Python运算符从低到高的优先顺序:

  Operator 操作员 Description 描述
lowest precedence最低优先级 oror Boolean OR 布尔或
andand Boolean AND 布尔AND
notnot Boolean NOT 布尔非
==, ==!=, !=<, <<=, <=>, >>=, >=is, isis notis not comparisons, identity 比较,身份
|| bitwise OR 按位或
^^ bitwise XOR 按位异或
&& bitwise AND 按位与
<<, <<>>>> bit shifts 位移
+, +-- addition, subtraction 加,减
*, */, ///, //%% multiplication, division, floor division, modulo 乘法,除法,底数除法,模
+x, +x-x, -x~x~x unary positive, unary negation, bitwise negation 一元肯定,一元否定,按位否定
highest precedence最高优先级 **** exponentiation 求幂

Operators at the top of the table have the lowest precedence, and those at the bottom of the table have the highest. Any operators in the same row of the table have equal precedence.

表格顶部的运算符的优先级最低,表格底部的运算符的优先级最高。 表的同一行中的所有运算符都具有相同的优先级。

It is clear why multiplication is performed first in the example above: multiplication has a higher precedence than addition.

很明显,为什么在上面的示例中首先执行乘法:乘法的优先级高于加法。

Similarly, in the example below, 3 is raised to the power of 4 first, which equals 81, and then the multiplications are carried out in order from left to right (2 * 81 * 5 = 810):

类似地,在下面的示例中,首先将3升为4的幂,等于81 ,然后按从左到右的顺序执行乘法( 2 * 81 * 5 = 810 ):

>>> >>>  2 2 * * 3 3 ** ** 4 4 * * 55810810

Operator precedence can be overridden using parentheses. Expressions in parentheses are always performed first, before expressions that are not parenthesized. Thus, the following happens:

运算符优先级可以使用括号来覆盖。 总是先执行括号中的表达式,然后再执行未括号中的表达式。 因此,发生以下情况:

In the first example, 20 + 4 is computed first, then the result is multiplied by 10. In the second example, 4 * 5 is calculated first, then 3 is raised to that power, then the result is multiplied by 2.

在第一个示例中,首先计算20 + 4 ,然后将结果乘以10 。 在第二个示例中,首先计算4 * 5 ,然后将3提高到该乘方,然后将结果乘以2

There is nothing wrong with making liberal use of parentheses, even when they aren’t necessary to change the order of evaluation. In fact, it is considered good practice, because it can make the code more readable, and it relieves the reader of having to recall operator precedence from memory. Consider the following:

随意使用括号没有什么错,即使不必更改括号的顺序也是如此。 实际上,这被认为是一种好习惯,因为它可以使代码更具可读性,并且使阅读者不必从内存中调用运算符优先级。 考虑以下:

(( a a < < 1010 ) ) and and (( b b > > 3030 ))

Here the parentheses are fully unnecessary, as the comparison operators have higher precedence than and does and would have been performed first anyhow. But some might consider the intent of the parenthesized version more immediately obvious than this version without parentheses:

这里的括号是完全没有必要的,因为比较运算符的优先级比and更高and并且无论如何都将首先执行。 但是有些人可能认为带括号的版本的意图比没有括号的版本更明显:

On the other hand, there are probably those who would prefer the latter; it’s a matter of personal preference. The point is, you can always use parentheses if you feel it makes the code more readable, even if they aren’t necessary to change the order of evaluation.

另一方面,可能有些人更喜欢后者。 这是个人喜好问题。 关键是,即使您不需要更改评估顺序,也可以使用括号来使代码更具可读性。

增值分配运算符 (Augmented Assignment Operators)

You have seen that a single equal sign (=) is used to assign a value to a variable. It is, of course, perfectly viable for the value to the right of the assignment to be an expression containing other variables:

您已经看到,使用单个等号( = )将值分配给变量。 当然,赋值右边的值是包含其他变量的表达式是完全可行的:

>>> >>>  a a = = 1010>>> >>>  b b = = 2020>>> >>>  c c = = a a * * 5 5 + + bb>>> >>>  cc7070

In fact, the expression to the right of the assignment can include references to the variable that is being assigned to:

实际上,赋值右边的表达式可以包括对分配给以下变量的引用:

The first example is interpreted as “a is assigned the current value of a plus 5,” effectively increasing the value of a by 5. The second reads “b is assigned the current value of b times 3,” effectively increasing the value of b threefold.

第一个例子将被解释为“ a被分配的当前值a5 ”,从而有效地增加的值a5 。 第二读出“ b被分配的当前值b3 ”,有效地增加了的值b三倍。

Of course, this sort of assignment only makes sense if the variable in question has already previously been assigned a value:

当然,这种分配仅在所讨论的变量先前已经分配了值时才有意义:

>>> >>>  z z = = z z / / 1212Traceback (most recent call last):  File Traceback (most recent call last):  File "
", line "
" , line 1, in 1 , in
z z = = z z / / 1212NameError: NameError : name 'z' is not definedname 'z' is not defined

Python supports a shorthand augmented assignment notation for these arithmetic and bitwise operators:

Python支持这些算术和按位运算符的简写增强分配表示法:

Arithmetic 算术 Bitwise 按位
++
--
**
//
%%
////
****
&&
||
^^
>>>>
<<<<

For these operators, the following are equivalent:

对于这些运算符,以下内容等效:

Take a look at these examples:

看下面的例子:

Augmented
Assignment
增强型
分配
Standard
Assignment
标准
分配
a += 5a += 5 is equivalent to 相当于 a = a + 5a = a + 5
a /= 10a /= 10 is equivalent to 相当于 a = a / 10a = a / 10
a ^= ba ^= b is equivalent to 相当于 a = a ^ ba = a ^ b

结论 (Conclusion)

In this tutorial, you learned about the diverse operators Python supports to combine objects into expressions.

在本教程中,您了解了Python支持将对象组合为表达式的各种运算符

Most of the examples you have seen so far have involved only simple atomic data, but you saw a brief introduction to the string data type. The next tutorial will explore string objects in much more detail.

到目前为止,您看到的大多数示例都只涉及简单的原子数据,但是您对字符串数据类型进行了简要介绍。 下一个教程将更详细地探讨字符串对象。

Don’t miss the follow up tutorial: and you’ll know when the next installment comes out.

不要错过后续教程: ,您将知道下一期的发行时间。

翻译自:

转载地址:http://edqwd.baihongyu.com/

你可能感兴趣的文章
mean shift博客推荐
查看>>
App Naver Line 5.3 add new features - "True Delete"
查看>>
shell中$0,$?,$!等的特殊用法
查看>>
jsp的page指令的错误页面跳转
查看>>
android用户界面之GridView教程实例汇总
查看>>
夺命雷公狗----Git---7---GitHub当仓库本地使用(完)
查看>>
.NET/ASP.NET Routing路由(深入解析路由系统架构原理)http://wangqingpei557.blog.51cto.com/1009349/1312422...
查看>>
647. Palindromic Substrings 互文的子字符串
查看>>
[poj2096]Collecting Bugs[概率dp]
查看>>
Mongodb数据导出工具mongoexport和导入工具mongoimport介绍(转)
查看>>
图片和视频操作核心代码
查看>>
css实现简单几何图形
查看>>
asp.net 2.0中实现异步处理任务.
查看>>
Java Cryptography Extension (JCE): 放开Java加密算法密钥最大长度16的限制
查看>>
苹果一体机发射Wi-Fi
查看>>
Unity3d使用未破解的TexturePacker
查看>>
一个菜鸟的总结
查看>>
20145309信息安全系统设计基础第9周学习总结上
查看>>
c# 字段、属性get set
查看>>
C#与C++交互的一些基础
查看>>