python3.x - Problem with Python not operator
phpcn_u1582
phpcn_u1582 2017-06-22 11:52:39
0
3
1277
>>> a = False + 5
5
>>> a = not(1) + 5
False

As above, when False is directly calculated, it will be calculated as 0.
When using the logical operator not, the value of not(1) is False or 0.

But why does the result of directly putting not(1) into the arithmetic operation and then calculating it again is False?
Is this related to Python’s algorithmic logic?

phpcn_u1582
phpcn_u1582

reply all(3)
刘奇

Because not is not a function, but an expression. No matter you not(1)+5 or not (1+5), its function is just to invert the subsequent result. .
For example:

>>> not 1 + 2
False

>>> not (1 + 2)
False

>>> not (1 + 2) + 1
False

>>> (not (1 + 2)) + 1
1
漂亮男人

Usage of not operator in Python Boolean Operations:

not x

if x is false, then True, else False

In addition, the precedence of the + operator is higher than that of the not operator, so in not(1) + 5, (1) + 5 is calculated first, and then (1)+5 serves as the operand of the not operator. For example, you can see:

not(-1)      # False
not(-1) + 1  # True
Peter_Zhu
正如上面所说,因为 not operator 的优先级小于 +  
所以 not(1)+6 会被翻译为 not (1)+5
关于这些情况,你完全可以通过 dis模块 来查看具体的过程。

>>> import dis
>>> dis.dis("a = False + 5")
  1           0 LOAD_CONST               3 (5)
              3 STORE_NAME               0 (a)
              6 LOAD_CONST               2 (None)
              9 RETURN_VALUE
>>> dis.dis("a = not(1) + 5")
  1           0 LOAD_CONST               3 (6)
              3 UNARY_NOT
              4 STORE_NAME               0 (a)
              7 LOAD_CONST               2 (None)
             10 RETURN_VALUE
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template