Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need some clarification on the ** operator in Python

I wanted to start by asking here about this. This was given to me as part of an exercise at codeacademy.com and confused me for the better part of an hour.

Take a look at the following code block:

bool_one = 40 / 20 * 4 >= -4**2

Now, I evaluated that as being "8 >= 16" which is False.

However, the codeacademy.com terminal says it's True. When I started writing debug code lines, I found the issue was in how "-4**2" gets evaluated. When I run it on the terminal at CodeAcademy as well as on my local linux system, "-4**2" in Python comes out to "-16"... which is contrary to everything I have learned in all my math classes as well as every single calculator I have run it on. Whether I run it as "-4 * -4" or "-4^2" or even, using the "x^y" key, "-4 [x^y] 2", it still comes out as "16". So, how is python coming out with "-16" for "-4**2"?

Can someone please clarify this for me?

TIA.

like image 634
ShadowCat8 Avatar asked Dec 25 '22 22:12

ShadowCat8


1 Answers

From the doc of Power Operator:

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:

power ::=  primary ["**" u_expr]

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.

Emphasis mine.

So, for getting the required result, you need to add parenthesis around -4.

>>> (-4) ** 2
16
like image 164
Rohit Jain Avatar answered Jan 06 '23 01:01

Rohit Jain