简体   繁体   English

为什么Python在if语句中将字符串/数字评估为True还是myNumber == True返回False?

[英]Why does Python evaluate strings/numbers as True in if statements yet myNumber == True returns False?

The following will print 'ok' : 以下将打印'ok'

if 5:
   print('ok')

Yet when I do: 然而当我这样做时:

print(5 == True) 

The output is False . 输出为False

The same thing happens with strings. 字符串也会发生同样的事情。 Why? 为什么?

You're testing different things here. 你在这里测试不同的东西。

The if just checks if the bool of the expression (see also "Truth value testing" ) is True not if the identity is equal to True . if只检查表达式的bool (参见“真值测试” )是否为True如果标识等于True

So what is actually tested by the if is: 那么if实际测试的是:

>>> bool(5) == True
True

True has value 1. If you set True = 5 (only in python 2) the equality become True. True具有值1.如果设置True = 5 (仅在python 2中),则等式变为True。 The 'if' statement is like it is checking if the guard is not 0 or None so every number not 0 is ok to enter in the first block. 'if'语句就像检查保护是不是0还是无,所以每个不是0的数字都可以输入第一个块。 In fact False has value 0. 实际上False的值为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM