semantics of ** (unexpected/inconsistent?)

Colin W. cjwilliams43 at gmail.com
Sun Nov 29 20:03:27 EST 2009


On 29-Nov-09 19:50 PM, Chris Rebert wrote:
> 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.
>>
>>
>>>>> -3**2
>> -9
>>
>>>>> x = -3
>>
>>>>> x**2
>> 9
>>>>>
>>
>> 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.
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
> [*] http://en.wikipedia.org/wiki/Concatenative_language
See the Operator Order of Precedence:
http://docs.python.org/reference/expressions.html#summary

Parentheses permit the user to vary the precedence.

Colin W.




More information about the Python-list mailing list