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


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to