semantics of ** (unexpected/inconsistent?)
clp2 at rebertia.com
Mon Nov 30 01:50:11 CET 2009
On Sun, Nov 29, 2009 at 4:39 PM, Esmail <ebonak at hotmail.com> wrote:
> Ok, this is somewhat unexpected:
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> x = -3
> I would have expected the same result in both cases.
> Initially I would have expected -3**2 to yield 9, but I can accept
> that ** binds tighter than the unary -, but shouldn't the results
> be consistent regardless if I use a literal or a variable?
_No_, because using the variable evaluates "-3" as a unit separately
by itself, before the exponentiation ever occurs; it's the same as the
difference between (-3)**2 and -3**2.
Python is not a concatenative programming language[*]; you can't
directly textually replace a variable with its value and expect to get
the same result from an expression. For instance, in this case, you
need to add the parentheses.
More information about the Python-list