Python 邏輯運算符優先順序(not,and,or)

先看案例:

>>> not 1 or 0 and 1 or 2 and 3 or 4 and 5

這條語句的結果是:3

而不是:5

因為 Python 中邏輯運算符有優先順序:

not > and > or

所以上述語事實上是:

>>> (not 1) or (0 and 1) or (2 and 3) or (4 and 5)

這裡需要注意,在 Python 中,4 and 5 的結果是 5,4 or 5 的結果是 4。

Tags: