为什么python中的函数为false?
我不明白为什么:为什么python中的函数为false?,python,boolean,Python,Boolean,我不明白为什么: f = lambda x: x In [8]: f is True Out[8]: False In [9]: not f is True Out[9]: True In [10]: f is False Out[10]: False In [11]: f is True Out[11]: False In [12]: not f Out[12]: False In [13]: not f is True Out[13]: True In [14]: not f
f = lambda x: x
In [8]: f is True
Out[8]: False
In [9]: not f is True
Out[9]: True
In [10]: f is False
Out[10]: False
In [11]: f is True
Out[11]: False
In [12]: not f
Out[12]: False
In [13]: not f is True
Out[13]: True
In [14]: not f is False
Out[14]: True
嗯。所以直到现在我们可以想象这是由于使用了“is”而不是“==”。如图所示:
In [15]: 0.00000 is 0
Out[15]: False
In [16]: 0.00000 == 0
Out[16]: True
嗯。但是,如果我在函数上这样做,为什么:
In [17]: not f == False
Out[17]: True
In [18]: not f == True
Out[18]: True
In [19]: f ==True
Out[19]: False
In [20]: f ==False
Out[20]: False
In [21]: f
Out[21]: <function __main__.<lambda>>
[17]中的not f==False
Out[17]:对
在[18]中:非f==True
Out[18]:对
在[19]中:f==True
Out[19]:假
在[20]中:f==False
Out[20]:假
In[21]:f
出[21]:
我试图解释它是因为“是”而不是“==”,但是例子19和20粉碎了我的逻辑。有人能解释一下吗?是对对象身份的测试。将True
以外的任何内容与is True
进行比较总是会出错
您的下一组测试测试是否not(f==False)
或not(f==True)
;同样,布尔对象只对自身进行相等测试,因此与==False
比较时,除False
之外的任何对象都将测试为False<代码>非假
则为真
您希望使用bool()
来测试某个内容是否正确:
>>> bool(f)
True
>>> bool(0)
False
不要用平等性测试来判断某件事是真是假
请注意,在Python中,只有数字0、空容器和字符串以及False
被视为False。默认情况下,在布尔上下文中,其他所有内容都被视为true。自定义类型可以实现(当为数字时)或(用于实现容器)来改变该行为。Python3将\uuuuuuuuuuuuuuuuuuuuuuu非零
替换为
函数没有
\uu非零
或\uu len\uuu
方法,所以它们总是被认为是真的。您自己的示例显示f为假
为假,所以我对您的标题感到困惑
为什么期望函数的计算结果等于布尔值?这难道不是一种奇怪的行为吗?如果你检查一个函数的“真实性”,你会发现它是真的
>>> f = lambda x: x
>>> bool(f)
True
您只是简单地将函数本身与
True
或False
进行比较,因为它是一个函数,所以它永远不会是这样的<代码>is检查身份。。。
函数是非假值,但它不等于真
def xyz():
pass
if xyz:
#this will trigger since a method is not a falsey value
xyz == True #No it is not equal to true
xyz == False #no it is not equal to false
xyz is True #no it certainly is not the same memory location as true
xyz is False #no it is also not the same memory location as false
这是特定于功能的吗?其他值如何与真值和假值进行比较?啊,太愚蠢了。忘记使用bool()比较布尔值。当然请删除您的第一句话,即
True为True
始终将False
。为什么?我希望它是真的
,我的翻译也同意。我知道你在说什么,但从字面上看,“除真的是真的
”以外的任何东西都很容易被误读(例如,意味着假的是假的
会是假的)。啊。我要么读得太快,要么答案的初稿没有。不管怎样,我都是罪过。谢谢。@NoufalIbrahim:[声明]之外的任何东西都是假的。如果你忘了一些括号if char.isdigit和char在['1','2']中时
vsif char.isdigit()和char在['1','2']中时