首頁  >  問答  >  主體

python3.x - Python not 運算子的問題

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

如上,將 False 直接進行運算時會作為 0 來計算。
使用邏輯運算子 not 時,not(1) 的值為 False0

但為什麼直接將 not(1) 放進算術運算後再次計算的結果為 False
這和 Python 的演算法邏輯有關麼?

phpcn_u1582phpcn_u15822675 天前1228

全部回覆(3)我來回復

  • 怪我咯

    怪我咯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

    回覆
    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

    回覆
    0
  • 天蓬老师

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

    雷雷

    回覆
    0
  • 取消回覆