After finishing our previous tutorial on Python variables 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变量的上一教程之后,您现在应该已经掌握了创建和命名不同类型的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: Click here to join the Real Python Newsletter and you’ll know when the next installment comes out.
不要错过后续教程: 单击此处加入Real Python Newslet ,您将知道下一期的发行时间。
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 = = 10
10
>>> >>> b b = = 20
20
>>> >>> a a + + b
b
30
30
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:
在这种情况下, +
运算符将操作数a
和b
在一起。 操作数可以是文字值或引用对象的变量:
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支持将数据对象组合为表达式的许多运算符。 这些将在下面进行探讨。
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 + b a + b |
Addition加成 | a and a 和b b 总和 |
||||
- (unary)- (一元) |
-a -a |
Unary Negation一元否定 | a but opposite in signa ,但符号相反 |
||||
- (binary)- (二进位) |
a - b a - b |
Subtraction减法 | b subtracted from b 从减去a a |
||||
* * |
a * b a * b |
Multiplication乘法 | a and a 和b b 乘积 |
||||
/ / |
a / b a / b |
Division师 | a is divided by a 除以b .b 。 The result always has type 结果始终为 float .float 类型。 |
||||
% % |
a % b a % b |
Modulus模量 | a is divided by a 除以b b 余数 |
||||
// // |
a // b a // b |
Floor Division (also called 地板部门 (也称为Integer Division)整数部门 ) | a is divided by a 除以b , rounded to the next smallest whole numberb ,四舍五入到下一个最小整数 |
||||
** ** |
a ** b a ** b |
Exponentiation求幂 | a raised to the power of a 提升为b b 的幂 |
Here are some examples of these operators in use:
以下是这些使用中的运算符的一些示例:
>>> >>> a a = = 4
4
>>> >>> b b = = 3
3
>>> >>> ++ a
a
4
4
>>> >>> -- b
b
-3
-3
>>> >>> a a + + b
b
7
7
>>> >>> a a - - b
b
1
1
>>> >>> a a * * b
b
12
12
>>> >>> a a / / b
b
1.3333333333333333
1.3333333333333333
>>> >>> a a % % b
b
1
1
>>> >>> a a ** ** b
b
64
64
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 / / 4
4
2.5
2.5
>>> >>> 10 10 // // 4
4
2
2
>>> >>> 10 10 // // -- 4
4
-3
-3
>>> >>> -- 10 10 // // 4
4
-3
-3
>>> >>> -- 10 10 // // -- 4
4
2
2
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()
来显示表达式的值,这与使用文字值或变量的方法相同:
Operator | 操作员 | Example | 例 | Meaning | 含义 | Result | 结果 |
---|---|---|---|---|---|---|---|
== == |
a == b a == b |
Equal to等于 | True if the value of True 如果值a is equal to the value of a 等于的值b b 否则为 False otherwiseFalse |
||||
!= != |
a != b a != b |
Not equal to不等于 | True if a 不等于a is not equal to b 为b True 否则为 False otherwiseFalse |
||||
< < |
a < b a < b |
Less than少于 | True if a 小于a is less than b 则为b True 否则为 False otherwiseFalse |
||||
<= <= |
a <= b a <= b |
Less than or equal to小于或等于 | True if a 小于或等于a is less than or equal to b 则为b True 否则为 False otherwiseFalse |
||||
> > |
a > b a > b |
Greater than比...更棒 | True if a 大于a is greater than b 则为b True 否则为 False otherwiseFalse |
||||
>= >= |
a >= b a >= b |
Greater than or equal to大于或等于 | True if a 大于或等于a is greater than or equal to b 则为b True 否则为 False otherwiseFalse |
Here are examples of the comparison operators in use:
以下是使用中的比较运算符的示例:
>>> >>> a a = = 10
10
>>> >>> b b = = 20
20
>>> >>> a a == == b
b
False
False
>>> >>> a a != != b
b
True
True
>>> >>> a a <= <= b
b
True
True
>>> >>> a a >= >= b
b
False
False
>>> >>> a a = = 30
30
>>> >>> b b = = 30
30
>>> >>> a a == == b
b
True
True
>>> >>> a a <= <= b
b
True
True
>>> >>> a a >= >= b
b
True
True
Comparison operators are typically used in Boolean contexts like conditional and loop statements to direct program flow, as you will see later.
比较运算符通常用于条件条件和循环语句等布尔上下文中,以引导程序流,这将在后面介绍。
Recall from the earlier discussion of floating-point numbers 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.1
和2.2
,因此您不能依靠x
与3.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.00001
0.00001
>>> >>> x x = = 1.1 1.1 + + 2.2
2.2
>>> >>> absabs (( x x - - 3.33.3 ) ) < < tolerance
tolerance
True
True
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()
返回绝对值。 如果两个数字之间的差的绝对值小于指定的公差,则它们彼此足够接近以被视为相等。
The logical operators not
, or
, and and
modify and join together expressions evaluated in Boolean context to create more complex conditions.
逻辑运算符not
,, or
和and
修改并将在布尔上下文中评估的表达式结合在一起以创建更复杂的条件。
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对象True
或False
。 考虑以下示例:
In the examples above, x < 10
, callable(x)
, and t
are all Boolean objects or expressions.
在上面的示例中, x < 10
, callable(x)
和t
都是布尔对象或表达式。
Interpretation of logical expressions involving not
, or
, and and
is straightforward when the operands are Boolean:
当操作数为布尔值时,涉及not
, or
和and
的逻辑表达式的解释很简单:
Operator | 操作员 | Example | 例 | Meaning | 含义 |
---|---|---|---|---|---|
not not |
not x not x |
True if True ,如果x is x 是False False 如果 False if x 为x is True 则为True False (Logically reverses the sense of (逻辑上反转 x )x 的含义) |
|||
or or |
x or y x or y |
True if either True 如果任一x or x 或y is y 是True True 否则为 False otherwiseFalse |
|||
and and |
x and y x and y |
True if both True 如果两个x and x 和y are y 是True True 否则为 False otherwiseFalse |
Take a look at how they work in practice below.
在下面查看它们在实践中的工作方式。
not
和布尔操作数 (not
and Boolean Operands) x = 5
x = 5
not x < 10
not x < 10
False
False
not callable(x)
not callable(x)
True
True
Operand | 操作数 | Value | 值 | Logical Expression | 逻辑表达 | Value | 值 |
---|---|---|---|---|---|---|---|
x < 10 x < 10 |
True True |
not x < 10 not x < 10 |
False False |
||||
callable(x) callable(x) |
False False |
not callable(x) not callable(x) |
True True |
or
和布尔操作数 (or
and Boolean Operands)Operand | 操作数 | Value | 值 | Operand | 操作数 | Value | 值 | Logical Expression | 逻辑表达 | Value | 值 |
---|---|---|---|---|---|---|---|---|---|---|---|
x < 10 x < 10 |
True True |
callable(x) callable(x) |
False False |
x < 10 or callable(x) x < 10 or callable(x) |
True True |
||||||
x < 0 x < 0 |
False False |
callable(x) callable(x) |
False False |
x < 0 or callable(x) x < 0 or callable(x) |
False False |
and
和布尔操作数 (and
and Boolean Operands) x = 5
x = 5
x < 10 and callable(x)
x < 10 and callable(x)
False
False
x < 10 and callable(len)
x < 10 and callable(len)
True
True
Operand | 操作数 | Value | 值 | Operand | 操作数 | Value | 值 | Logical Expression | 逻辑表达 | Value | 值 |
---|---|---|---|---|---|---|---|---|---|---|---|
x < 10 x < 10 |
True True |
callable(x) callable(x) |
False False |
x < 10 and callable(x) x < 10 and callable(x) |
False False |
||||||
x < 10 x < 10 |
True True |
callable(len) callable(len) |
True True |
x < 10 or callable(len) x < 10 or callable(len) |
True True |
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.”
许多对象和表达式不等于True
或False
。 但是,它们仍可以在布尔上下文中进行评估,并确定为“真实”或“虚假”。
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中,它是明确定义的。 在布尔上下文中进行评估时,以下所有内容均被视为错误:
False
0
, 0.0
, 0.0+0.0j
)None
False
0
, 0.0
, 0.0+0.0j
) 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
。
A zero value is false. A non-zero value is true.
零值为假。 非零值是true。
An empty string is false. A non-empty string is true.
空字符串为false。 非空字符串为true。
>>> >>> printprint (( boolbool (( '''' ), ), boolbool (( """" ), ), boolbool (( """""""""""" ))
))
False False False
False False False
>>> >>> printprint (( boolbool (( 'foo''foo' ), ), boolbool (( " "" " ), ), boolbool (( ''' '''''' ''' ))
))
True True True
True True True
Python provides built-in composite data types called
list
,tuple
,dict
, andset
. 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提供了称为
list
,tuple
,dict
和set
内置复合数据类型。 这些是包含其他对象的“容器”类型。 这些类型之一的对象如果为空,则视为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
, andset
types, see the upcoming tutorials.有关
list
,tuple
,dict
和set
类型的更多信息,请参见后续教程。
None
关键字 (None
Keyword)None
is always false:
None
一个总是错误的:
>>> >>> boolbool (( NoneNone )
)
False
False
Non-Boolean values can also be modified and joined by not
, or
and, and
. The result depends on the “truthiness” of the operands.
非布尔值也可以通过not
, or
和and
进行修改和连接。 结果取决于操作数的“真实性”。
not
和非布尔操作数 (not
and Non-Boolean Operands)Here is what happens for a non-Boolean value x
:
这是非布尔值x
:
x isx 是 |
not x isnot x 是 |
|
---|---|---|
“truthy” | “真” | False False |
“falsy” | “虚假” | True True |
Here are some concrete examples:
以下是一些具体示例:
or
和非布尔操作数 (or
and Non-Boolean Operands)This is what happens for two non-Boolean values x
and y
:
这是两个非布尔值x
和y
发生的情况:
x isx 是 |
x or y isx or y 为 |
|
---|---|---|
truthy | 真实的 | x x |
falsy | 虚假的 | y y |
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
不是True
或False
,而是x
或y
:
>>> >>> x x = = 3
3
>>> >>> y y = = 4
4
>>> >>> x x or or y
y
3
3
>>> >>> x x = = 0.0
0.0
>>> >>> y y = = 4.4
4.4
>>> >>> x x or or y
y
4.4
4.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如果任一x
或y
是truthy,和falsy如果两个x
和y
是falsy。
and
与非布尔操作数 (and
and Non-Boolean Operands)Here’s what you’ll get for two non-Boolean values x
and y
:
这是两个非布尔值x
和y
:
x isx 是 |
x and y isx and y 为 |
|
---|---|---|
“truthy” | “真” | y y |
“falsy” | “虚假” | x x |
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
取值不会为True
或False
,而是取值为x
或y
。 x and y
将truthy如果两个x
和y
是truthy,和falsy否则。
So far, you have seen expressions with only a single or
or and
operator and two operands:
到目前为止,您已经看到只有一个or
或and
运算符和两个操作数的表达式:
x x or or y
y
x x and and y
y
Multiple logical operators and operands can be strung together to form compound logical expressions.
多个逻辑运算符和操作数可以串在一起形成复合逻辑表达式。
or
表达式 (Compound or
Expressions)Consider the following expression:
考虑以下表达式:
x1
or
x2or
x3or
… xnx 1
or
x 2or
x 3or
… x n
This expression is true if any of the xi are true.
如果x i中的任何一个为真,则该表达式为真。
In an expression like this, Python uses a methodology called short-circuit evaluation, 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.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) = 1
1
1
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
x2and
x3and
… xnx 1
and
x 2and
x 3and
… x 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)
调用。 False
和0.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'
There are some common idiomatic patterns that exploit short-circuit evaluation for conciseness of expression.
有一些常见的惯用模式,它们利用短路评估来简化表达。
Suppose you have defined two variables a
and b
, and you want to know whether (b / a) > 0
:
假设您已经定义了两个变量a
和b
,并且想知道(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 = = 0
0
>>> >>> b b = = 1
1
>>> >>> (( b b / / aa ) ) > > 0
0
Traceback (most recent call last):
File Traceback (most recent call last):
File "" , line "" , line 1, in 1 , in
(( b b / / aa ) ) > > 0
0
ZeroDivisionError: ZeroDivisionError : division by zero
division 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.
当a
为0
, a != 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
:
如果事实是这样,那么您甚至可以更加简洁。 当a
为0
,表达式a
本身就是虚假的。 无需显式比较a != 0
:
>>> >>> a a = = 0
0
>>> >>> b b = = 1
1
>>> >>> a a and and (( b b / / aa ) ) > > 0
0
0
0
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 '
will be true at that point. Evaluation stops, and the value of string
is returned and assigned to s
:
如果string
为非空,则为true,此时表达式string or '
将为true。 评估停止, string
值返回并分配给s
:
>>> >>> string string = = 'foo bar'
'foo bar'
>>> >>> s s = = string string or or ''
''
>>> >>> s
s
'foo bar'
'foo bar'
On the other hand, if string
is an empty string, it is falsy. Evaluation of string or '
continues to the next operand, '
, which is returned and assigned to s
:
另一方面,如果string
为空字符串,则为假。 string or '
求值继续到下一个操作数'
,该操作数返回并分配给s
:
Comparison operators can be chained together to arbitrary length. For example, the following expressions are nearly equivalent:
比较运算符可以链接到任意长度。 例如,以下表达式几乎等效:
x x < < y y <= <= z
z
x x < < y y and and y y <= <= z
z
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 <= z
, y
仅被评估一次。 较长的表达式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 x2
and
x2op2 x3and
… xn-1opn xnx 1 op 1 x 2
and
x 2 op 2 x 3and
…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 treat operands as sequences of binary digits and operate on them bit by bit. The following operators are supported:
按位运算符将操作数视为二进制数字序列,并对其进行逐位操作。 支持以下运算符:
Operator | 操作员 | Example | 例 | Meaning | 含义 | Result | 结果 |
---|---|---|---|---|---|---|---|
& & |
a & b a & b |
AND与 | AND of the bits in the corresponding position of the operands. (与 。 ( 1 if both are 1 如果两者都1 , otherwise 1 ,否则0 .)0 )。 |
||||
| | |
a | b a | 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 如果0 , 0 ,如果1 )。 |
|||
^ ^ |
a ^ b a ^ 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 >> n a >> n |
Shift right 向右移 n n places位 |
n places.n 位。 |
||||
<< << |
a << n a << 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()
方法。 现在,只需要注意按位运算的操作数和结果。
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提供了两个操作符, is
和is 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:
在此, x
和y
均指值为1001
对象。 他们是平等的。 但是,它们没有引用相同的对象,因此您可以验证:
>>> >>> idid (( xx )
)
60307920
60307920
>>> >>> idid (( yy )
)
60307936
60307936
x
and y
do not have the same identity, and x is y
returns False
.
x
和y
不具有相同的标识,并且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.
在这种情况下,由于a
和b
引用相同的对象,因此可以推论a
和b
也将相等。
Unsurprisingly, the opposite of is
is is not
:
不出所料,相反is
是is not
:
>>> >>> x x = = 10
10
>>> >>> y y = = 20
20
>>> >>> x x is is not not y
y
True
True
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最低优先级 | or or |
Boolean OR | 布尔或 | ||
and and |
Boolean AND | 布尔AND | |||
not not |
Boolean NOT | 布尔非 | |||
== , == , != , != , < , < , <= , <= , > , > , >= , >= , is , is , is not is 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 * * 5
5
810
810
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.
另一方面,可能有些人更喜欢后者。 这是个人喜好问题。 关键是,即使您不需要更改评估顺序,也可以使用括号来使代码更具可读性。
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 = = 10
10
>>> >>> b b = = 20
20
>>> >>> c c = = a a * * 5 5 + + b
b
>>> >>> c
c
70
70
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
被分配的当前值a
加5
”,从而有效地增加的值a
由5
。 第二读出“ b
被分配的当前值b
倍3
”,有效地增加了的值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 / / 12
12
Traceback (most recent call last):
File Traceback (most recent call last):
File "" , line "" , line 1, in 1 , in
z z = = z z / / 12
12
NameError: NameError : name 'z' is not defined
name '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 += 5 a += 5 |
is equivalent to | 相当于 | a = a + 5 a = a + 5 |
||
a /= 10 a /= 10 |
is equivalent to | 相当于 | a = a / 10 a = a / 10 |
||
a ^= b a ^= b |
is equivalent to | 相当于 | a = a ^ b a = a ^ b |
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: Click here to join the Real Python Newsletter and you’ll know when the next installment comes out.
不要错过后续教程: 单击此处加入Real Python Newslet ,您将知道下一期的发行时间。
翻译自: https://www.pybloggers.com/2018/06/operators-and-expressions-in-python/