semantics of ** (unexpected/inconsistent?)

Ben Finney ben+python at benfinney.id.au
Mon Nov 30 02:10:47 CET 2009


Esmail <ebonak at hotmail.com> writes:

> Brian J Mingus wrote:
> >
> >
> >
> > I think you answered your own question. 3**2 comes first in the
> > order of operations, followed by the negation.
>
> No, that's not the problem, I'm ok with the operator precedence of - vs **
>
> My problem is why I don't get the same result if I use the literal -3
> or a variable that contains -3 (x in my example).

You seem to be confusing the values, which (in this case) are numbers,
with their incidental representation in Python code, which is literal
expressions in text. Perhaps the following dissection will help:

    >>> -3**2

The expression ‘-3**2’ is evaluated, and a single value is the result.
In that expression, there are two operators: the unary-minus operator
and the exponential operator. There are two values as parameters in the
expression: the natural number three, and the natural number two.

    >>> x = -3

The expression ‘-3’ is evaluated, and a single value is the result. That
value has an internal representation of “the integer that is three less
than zero”. It is *not* the sequence of characters that you see in the
Python code; it is a number.

The name ‘x’ is then bound to that value.

    >>> x**2

The expression ‘x**2’ is evaluated, and a single value is the result. In
that expression, there is *one* operator: the exponential operator.
There is no unary-minus operator in the expression. There are two values
as parameters in the expression: the value referenced by the name ‘x’
which is the integer negative-three, and the natural number two.

I hope that explains the difference in behaviour.

-- 
 \          “I don't like country music, but I don't mean to denigrate |
  `\          those who do. And for the people who like country music, |
_o__)                        denigrate means ‘put down’.” —Bob Newhart |
Ben Finney



More information about the Python-list mailing list