Python 沒有 ! 運算符。not 是邏輯非關鍵字,!= 是不等於比較運算符。兩者用途、優先級、操作數類型完全不同。
| 特性 | 說明 |
|---|---|
| 類型 | 關鍵字(非運算符) |
| 操作數 | 任意對象(按真值判斷) |
| 返回值 | 布爾值 True / False |
| 優先級 | 低(低於比較運算符) |
| 短路求值 | 是 |
# 以下為 False
not True
not 1
not "non-empty"
not [1, 2]
not {"a": 1}
# 以下為 True
not False
not 0
not ""
not []
not {}
not None
# 條件判斷
if not user.is_active:
deny_access()
# 列表推導式過濾
active_users = [u for u in users if not u.is_banned]
# 組合邏輯
if not (a > 0 and b < 10):
...
| 特性 | 說明 |
|---|---|
| 類型 | 二元比較運算符 |
| 操作數 | 兩側對象(支持自定義 __ne__) |
| 返回值 | 布爾值 True / False |
| 優先級 | 高(高於 not) |
# 數值比較
5 != 3 # True
# 字符串比較
"abc" != "def" # True
# 自定義類
class Point:
def __init__(self, x, y): self.x, self.y = x, y
def __eq__(self, other): return self.x == other.x and self.y == other.y
# Python 3 自動提供 __ne__ 邏輯非 __eq__
p1, p2 = Point(1,2), Point(1,3)
p1 != p2 # True
| 語言 | 邏輯非 | 位非 | 不等於 |
|---|---|---|---|
| C/C++ | ! | ~ | != |
| Java | ! | ~ | != |
| Python | not | ~ | != |
關鍵差異:
! 作用於布爾/整數(0 為假),返回整數 0/1not 作用於任意對象,嚴格返回 bool~ 是位非(按位取反),僅適用整數:~5 == -6
# ❌ 錯誤:嘗試使用 !
# if !condition: # SyntaxError
# ✅ 正確
if not condition:
# ⚠️ 注意優先級
not a == b # 等價於 not (a == b)
not a is b # 等價於 not (a is b)
not a in b # 等價於 not (a in b) -- Python 特殊語法糖
# 位非陷阱
~True # -2 (按位取反,非邏輯非)
~False # -1
not:可讀性最強,符合 Python 哲學!=:語義明確,支持鏈式比較 a != b != cnot x == y:改用 x != y,更直觀~:僅用於整數位操作,勿混淆__eq__:Python 3 自動推導 __ne__Python 用 not 實現邏輯非,返回嚴格布爾值;!= 是不等於比較;~ 是位非。三者互不替代,語義、優先級、適用域截然不同。從 C/Java 轉 Python 時,務必拋棄 ! 習慣,擁抱 not 的可讀性優勢。