[Tutor] revisiting a puzzle about -3**2 vs (-3)**2
Emile van Sebille
emile at fenx.com
Wed Aug 12 19:54:07 CEST 2015
On 8/12/2015 9:07 AM, D Wyatt wrote:
> so I 'get' that -5**2 = -25 and (-5)**2 is 25, BUT if you write a function
>
> def sq(x):
> """ Output: sq returns the square of its input
> input x: a number (int or float)
> """
> return x**2
>
> and pass it a negative number it handles it as though the argument is
> in parentheses.
>
> I find this confusing. Can someone explain?
the passed in number is a single object. But when parsing a line,
"-5**2", exponentiation happens first, then negation of the result. The
parens around the -5 force evaluation as a number.
Consider this:
def sq1(x):
sgn = int(x<0)
return sgn*abs(x)**2
That's effectively what the parser does.
Emile
More information about the Tutor
mailing list