5.7 深入条件控制 More on Conditions

The conditions used in while and if statements above can contain other operators besides comparisons.

用于 whileif 语句的条件包括了比较之外的操作符。

The comparison operators in and not in check whether a value occurs (does not occur) in a sequence. The operators is and is not compare whether two objects are really the same object; this only matters for mutable objects like lists. All comparison operators have the same priority, which is lower than that of all numerical operators.

innot in 比较操作符审核值是否在一个区间之内。操作符 is is not 和比较两个对象是否相同;这只和诸如链表这样的可变对象有关。所有的比较操作符具有相同的优先级,低于所有的数值操作。

Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c.

比较操作可以传递。例如 a < b == c 审核是否 a 小于 bb 等于c

Comparisons may be combined by the Boolean operators and and or, and the outcome of a comparison (or of any other Boolean expression) may be negated with not. These all have lower priorities than comparison operators again; between them, not has the highest priority, and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C. Of course, parentheses can be used to express the desired composition.

比较操作可以通过逻辑操作符 andor组合,比较的结果可以用 not 来取反义。这些操作符的优先级又低于比较操作符,在它们之中, not 具有最高的优先级, or 优先级最低,所以A and not B or C 等于 (A and (not B)) or C。当然,表达式可以用期望的方式表示。

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. In general, the return value of a short-circuit operator, when used as a general value and not as a Boolean, is the last evaluated argument.

逻辑操作符 andor 也称作短路操作符:它们的参数从左向右解析,一旦结果可以确定就停止。例如,如果 AC 为真而 B 为假, A and B and C 不会解析 C。作用于一个普通的非逻辑值时,短路操作符的返回值通常是最后一个变量。

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

可以把比较或其它逻辑表达式的返回值赋给一个变量,例如:

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

需要注意的是Python与C不同,在表达式内部不能赋值。C 程序员经常对此抱怨,不过它避免了一类在C程序中司空见惯的错误:想要在解析式中使 == 时误用了 = 操作符。