Heim  >  Fragen und Antworten  >  Hauptteil

python3.x – Problem mit Python, kein Operator

>>> a = False + 5
5
>>> a = not(1) + 5
False

Wie oben, wird False 直接进行运算时会作为 0 来计算。
使用逻辑运算符 not 时,not(1) 的值为 False0.

Aber warum direkt not(1) 放进算术运算后再次计算的结果为 False hinzufügen?
Hängt das mit der algorithmischen Logik von Python zusammen?

phpcn_u1582phpcn_u15822675 Tage vor1227

Antworte allen(3)Ich werde antworten

  • 怪我咯

    怪我咯2017-06-22 11:54:39

    因为not不是一个函数, 是一个表达式, 不管你not(1)+5 还是 not (1+5), 它的作用也只是将后面的结果取反而已.
    例如:

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

    Antwort
    0
  • 漂亮男人

    漂亮男人2017-06-22 11:54:39

    Python 中 not 运算符的用法Boolean Operations:

    not x

    if x is false, then True, else False

    此外,+运算符的优先级(precedence)高于not运算符,所以not(1) + 5中先计算(1) + 5, 后面的(1)+5作为not运算符的操作数. 举个例子可以看到:

    not(-1)      # False
    not(-1) + 1  # True

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-06-22 11:54:39

    正如上面所说,因为 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
    

    Antwort
    0
  • StornierenAntwort