gpt4 book ai didi

python - 为什么不真实 == 真实 :

转载 作者:太空狗 更新时间:2023-10-30 00:41:36 26 4
gpt4 key购买 nike

风格指南的最后一点 http://www.python.org/dev/peps/pep-0008

读...

不要使用 == 将 bool 值与 True 或 False 进行比较。

为什么?

编辑只是为了弄清楚我在问什么(这表明问题本身),当你写

if something:
print "something is true"

您正在对 bool 值进行隐式转换,这可能有效也可能无效,具体取决于 true 的含义。恕我直言,不鼓励这种形式的编程,因为它可能导致副作用。

numberOfApples = -1
if numberOfApples:
print "you have apples" # is not what is intended.

if numberOfApples == True:
print "you have apples" # is also not what is intended.

iHaveApples = numberOfApples > 0
if iHaveApples is True: # Edit: corrected this.. the "is" is better than the ==
print "you have apples" # is correct.

隐式转换掩盖了逻辑错误。那么为什么风格指南鼓励这样做呢?

最佳答案

这意味着你应该写

if greeting:

代替:

if greeting == True:

同样,你也不应该这样写:

if (greeting == True) == True:

额外的测试是多余的,不会为代码增加任何值(value),因此应将其删除。

关于python - 为什么不真实 == 真实 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10222516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com