在 Python 中,! 是一个逻辑运算符,在 Python 中表示为 not, 用于表示 "非" 或 "不是"。它的优先级相对较高,仅次于括号和指数运算符。以下是 Python 运算符的优先级列表,从最高优先级(最具约束力)到最低优先级(最少约束力)¹²:
()括号**指数+x, -x, ~x一元加、一元减、按位取反*, /, //, %乘法、除法、整除、取模+, -加法、减法<<, >>位移运算符&按位与^按位异或|按位或==, !=, >, >=, <, <=, is, is not, in, not in比较、身份、成员运算符not逻辑非and逻辑与or逻辑或
因此,!(在 Python 中表示为 not)的优先级低于算术运算符(如 +, -, *, / 等),但高于 and 和 or。这意味着在没有括号的情况下,not 会先于 and 和 or 运算,但后于算术运算。例如:
print(not 1 + 1) # 输出 False,因为 1 + 1 = 2,not 2 = False
print(not 1 or 0) # 输出 False,因为 not 1 = False,False or 0 = False希望这个解释能帮助你理解 Python 中 ! 的优先级。如果你还有其他问题,欢迎随时向我提问。¹²
源: 与必应的对话, 2023/12/26 (1) 6. Expressions — Python 3.12.1 documentation. https://docs.python.org/3/reference/expressions.html. (2) Precedence and Associativity of Operators in Python - Programiz. https://www.programiz.com/python-programming/precedence-associativity. (3) Operator Precedence in Python - Python Geeks. https://pythongeeks.org/python-operator-precedence/.










