python – weird results with exponent operator in idle

Question:

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
Asked By: user1026169

||

Answers:

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

>>> -1 ** 2
-1
>>> -(1 ** 2)
-1
>>> (-1) ** 2
1
Answered By: Samwise

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
Answered By: I'mahdi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.