指数为 Python 的负数

Negative numbers with exponents in Python

为什么 Python 会给我 2 个不同的答案?

print(-1**2)   # prints -1 
print((-1)**2) # prints 1

Python 按以下顺序解析 print(-1**2)

  1. 获取 1 ** 2

    的指数
  2. 否定结果。

所以就变成了这样:

>>> -(1 ** 2)
-1
>>> 

因为 -1 转换为 print(0 - 1 ** 2)。但在运算顺序上table,**(指数)比-.

排名靠前

因此,Python数学遵循常规数学中的运算顺序,**更强大(优先于)-

Wikipedia 所述:

The acronym PEMDAS is common. It stands for Parentheses, Exponents, Multiplication/Division, Addition/Subtraction.

Python Docs上也提到:

Operator Description
(expressions...), [expressions...], {key: value...}, {expressions...} Binding or parenthesized expression, list display, dictionary display, set display
x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference
await x Await expression
** Exponentiation
+x, -x, ~x Positive, negative, bitwise NOT
*, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder 6

** 运算符在 - 上有 precedence,所以 -1**2 实际上是 -(1**2)

python 中的运算符优先级列表,从最高优先级(顶部)到最低优先级(底部):

Operator Function
() Parentheses (grouping)
f(args...) Function call
x[index:index] Slicing
x[index] Subscription
x.attribute Attribute reference
** Exponentiation
~x Bitwise not
+x, -x Positive, negative
*, /, % Multiplication, division, remainder
+, - Addition, subtraction
<<, >> Bitwise shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=, <>, !=, == Comparisons, membership, identity
not x Boolean NOT
and Boolean AND
or Boolean OR
lambda Lambda expression