Python “如何”;及;及;或;运算符使用0和1以及2、3、4等数字

Python “如何”;及;及;或;运算符使用0和1以及2、3、4等数字,python,python-3.x,Python,Python 3.x,我正在使用python 3.6.1 问题1: (A) 那样 False or 0 # gives 0, but 0 or False # gives False (both answers must be False) 为什么不是所有结果都为假,而是一个结果为0(数字) 同样地 (B) 为什么“B”情况下的所有结果都不是真的,第一个结果是1? 为什么它会给出整数1和0作为结果(情况A和B)? 这里面有什么方向吗 问题2: 除0和1以外的数字(如2,3,4,-2,-3)是否以任何方式表示Fal

我正在使用python 3.6.1

问题1: (A) 那样

False or 0 # gives 0, but

0 or False # gives False (both answers must be False)
为什么不是所有结果都为假,而是一个结果为0(数字)

同样地

(B) 为什么“B”情况下的所有结果都不是真的,第一个结果是1? 为什么它会给出整数1和0作为结果(情况A和B)? 这里面有什么方向吗

问题2: 除0和1以外的数字(如2,3,4,-2,-3)是否以任何方式表示
False
True

(C) (D) 其他整数(如2,3等)是否视为
False

为什么在情况D
2
而不是
True
False
时会输出它?

以及
都是布尔运算符,它们的行为解释如下:

表达式
x和y
首先计算x;如果x为false,则返回其值;否则,计算y并返回结果值

表达式
x或y
首先计算x;如果x为true,则返回其值;否则,计算y并返回结果值

如果这些是函数,它们看起来(大致)如下:

def and_function(x, y):
    if bool(x) == False:  # if x is false, its value is returned
        return x
    else:                 # otherwise, y is evaluated and the resulting value is returned
        return y     

def or_function(x, y):
    if bool(x) == True:  # if x is true, its value is returned
        return x     
    else:                # otherwise, y is evaluated and the resulting value is returned.
        return y     
因此,根据左侧的真值,这些值将始终计算为
x
y

在此上下文中,“evaluate”指的是表达式,而不是布尔值。因此,如果
bool(x)==True
,则
x或somefunction()
不会计算
somefunction()
。这就是等效函数失败的地方,因为这些函数不会推迟表达式的计算。所以不要把这两个函数看得太重。他们只是作为解释的助手


说明了如何定义数字的真值:

[…]以下值被认为是错误的:

  • False

  • 任何数字类型的零,例如0、0.0、0j

  • [……]

所有其他值都被认为是真的-因此许多类型的对象总是真的


然后,您询问布尔值
True
False
与数字之间的相等性。要理解这一点,您必须知道bools是Python中整数的一个子类。从某种意义上说,
True
只是
1
False
的另一个名称。因此,
True==1
False==0
都是
True
也就不足为奇了


注意:如果您来自其他语言,那么声明Python中没有用于比较的隐式转换可能很重要,我在另一个答案中详细解释了这一点:。

您能编辑您的问题并使其可读吗?您还可以将文本片段标记为代码,以便它们在视觉上突出。这个问题将被关闭,因为它在当前形式中不清楚/太宽泛。如果您只问一个明确的问题,则可以用相应的副本进行标记
True and 1 # gives 1, but

1 and True # gives True
True == 1 # gives True 

True == 2 # gives False, but

True and 2 # gives False.
False or 2 # gives 2

2 or False # gives 2
def and_function(x, y):
    if bool(x) == False:  # if x is false, its value is returned
        return x
    else:                 # otherwise, y is evaluated and the resulting value is returned
        return y     

def or_function(x, y):
    if bool(x) == True:  # if x is true, its value is returned
        return x     
    else:                # otherwise, y is evaluated and the resulting value is returned.
        return y