Home > OS >  python - weird results with exponent operator in idle
python - weird results with exponent operator in idle

Time:07-24

I'm getting a strange result when squaring -1 in idle. What's going on?

Unexpected result:

>>>| -1 ** 2
>>>| -1

Expected result:

>>>| pow(-1,2)
>>>| 1

>>>| my_var = -1
>>>| my_var **= 2
>>>| my_var
>>>| 1

CodePudding user response:

Operator precedence (the - is a unary minus operator):

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

CodePudding user response:

This happens occurs because of Precedence Operators:

  1. () Parentheses
  2. ** Exponent
  3. x, -x, ~x Unary plus, Unary minus, Bitwise NOT
  4. *, /, //, % Multiplication, Division, Floor division, Modulus
  5. , - Addition, Subtraction

you can get what you want like below, In The question first ** then compute Unary minus for solving you need to use higher precedence like () Parentheses.

>>> (-1) ** 2
1
  • Related