semantics of ** (unexpected/inconsistent?)

E

Esmail

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.


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?
 
A

Alf P. Steinbach

* Esmail:
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.


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?

It is.

:)


I guess you expect your expression "x**2" to somehow be evaluated as "-3**2".
But x doesn't contain text, it contains an integer value that presumably (I
don't know) is represented in the binary number system, so it's evaluated as
"(-3)**2". If x contained text and was evaluated as such, pure text replacement,
then you should be able to write 2 x and have that evaluated as "2 -x"...


Cheers & hth.,

- Alf
 
M

Mel

Esmail said:
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.


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?

When you say ** binds tighter than unary -, you're also saying that -3 isn't
a literal: it's an expression. Try

y=3
-y**2

Mel.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,231
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top