-2

Can someone explain the difference between these two expressions in Python:

(-1)**2 == 1
-1**2 == -1

Why do the parentheses change the outcome?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 7
    Double check the operator precedence of the unary `-` and `**` operators. – Carcigenicate Jun 06 '21 at 14:45
  • Python first calculates the power according to operator precedence and then the - –  Jun 06 '21 at 14:55
  • 2
    This is a math question, not for coding. – Buddy Bob Jun 06 '21 at 14:56
  • Both equations yield 1 as the result on a calculator. As other answers have shown, it's because of the way python completes the ** operator and then interprets the - after. Thus this is a python question. – Marzo Buffon Jun 06 '21 at 15:19
  • See documentation on [operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence). – martineau Jun 06 '21 at 15:40

1 Answers1

1

The parentheses means the whole value inside is will be raised to the power 2.

(-1)**2 == 1

So -1*-1 is 1 No parentheses means the - will be taken out of the equation and added to the end of the answer.

1) -1**2
2) 1**2 
3) 1
4) -1

Python handles this the same way the world does :)

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44