Python 'not' 操作符

问题描述 投票:-1回答:4
x = 0

if not x:
    print(bool(x))
    print("Evaluated True")

else:
    print(bool(x))
    print("Evaluated False")

产量

False
Evaluated True

为什么不执行 else 块呢,我认为 x = 0 是 False,而不是x是 True. 还是我误解了布尔值的定义?

python boolean boolean-logic
4个回答
2
投票

你必须打印你的if表达式 "not x"。然后你看到not x == not False == True。

x = 0

if not x:
    print(bool(not x))
    print("Evaluated True")

else:
    print(bool(not x))
    print("Evaluated False")

答:你的答案是:"不是x"。

True
Evaluated True

2
投票
>>> x = 0
>>> if x:
...   print(bool(x), "Evaluated True")
... else:
...   print(bool(x),"Evaluated False")
... 
False Evaluated False

注意: 除了0之外,所有整数的布尔值都是True。


1
投票

当if语句里面的表达式为真时,if块就会被执行。由于x为0,那么 not x 是true,这意味着if块将被执行,而不是 else块。

print(bool(x))将打印false,因为x是0。


1
投票

因此,就像你说的那样,if语句会被执行。not x == True 所以if语句会被执行


1
投票
if not x

这是真的,这就是为什么if后面的那行会被执行。因此,else语句没有被执行。只有当if语句为false时才会被执行。


1
投票

除了0之外,所有的布尔值都是真。not x == True 所以它被评估为 true.


1
投票
False
Evaluated True

你的输出是正确的.你的布尔概念是正确的(x=0是False,而不是x是True。)但你的实现是错误的。

x = 0

if not x:
    print(bool(x))
    print("Evaluated True")

在你的代码中

if not x 是指 if (not x)==True 这是绝对正确的,因此if条件运行。

使用 if (some condition) 有时是很棘手的。它有时也是由于没有括号。

你可以用这个方法来实现所需的输出 if (not x)==False.

© www.soinside.com 2019 - 2024. All rights reserved.