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
Answers:
Operator precedence (the -
is a unary minus operator):
>>> -1 ** 2
-1
>>> -(1 ** 2)
-1
>>> (-1) ** 2
1
This happens occurs because of Precedence Operators:
()
Parentheses
**
Exponent
+x
, -x
, ~x
Unary plus, Unary minus, Bitwise NOT
*
, /
, //
, %
Multiplication, Division, Floor division, Modulus
+
, -
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
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
Operator precedence (the -
is a unary minus operator):
>>> -1 ** 2
-1
>>> -(1 ** 2)
-1
>>> (-1) ** 2
1
This happens occurs because of Precedence Operators:
()
Parentheses**
Exponent+x
,-x
,~x
Unary plus, Unary minus, Bitwise NOT*
,/
,//
,%
Multiplication, Division, Floor division, Modulus+
,-
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