[Tutor] revisiting a puzzle about -3**2 vs (-3)**2

Alan Gauld alan.gauld at btinternet.com
Wed Aug 12 19:45:35 CEST 2015


On 12/08/15 17:07, 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.

Of course it does.

x**2 => (x)**2

If you assigned a value to x like this:

x = -3
print x**2

You would expect it (I hope) to be treated as

print (x)**2

would you not?

That's what the function does.

Otherwise the function would, effectively,
have to do this, which would be very inconsistent.

if x < 0: return -(x**2)
else: return x**2

By passing a negative number (-3 say) into the function
you are effectively putting it in parens - you are saying
you want the square of -3

Neither are you passing in the string '-3' which then
gets pre-pended to '**2' and then evaluated.
You are passing in a single integer value.

It's the same with the builtin pow() function

 >>> pow(-3, 2)
9

I'm explicitly telling Python I want the value -3 raised
to the power 2.

If I write

-3**2

I'm telling Python to interpret the expression -3**2 according
to its language rules - which it does as -(3**2).


> Also, can someone please take me off moderated?

Done :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list