Python Exponent Question
Robert Kern
robert.kern at gmail.com
Mon Dec 10 13:28:42 EST 2007
databyss wrote:
> I have a simple program and the output isn't what I expect. Could
> somebody please explain why?
>
> Here's the code:
>
> #simple program
> print "v = 2"
> v = 2
> print "v**v = 2**2 =", v**v
> print "v**v**v = 2**2**2 =", v**v**v
> print "v**v**v**v = 2**2**2**2 =", v**v**v**v
> #end program
>
> Here's the output:
>
> v = 2
> v**v = 2**2 = 4
> v**v**v = 2**2**2 = 16
> v**v**v**v = 2**2**2**2 = 65536
>
> I would expect 2**2**2**2 to be 256
Exponentiation is right-associative. I.e. 2**2**2**2 == 2**(2**(2**2))
The reason is that left-associativity is better written with multiplication.
(x**y)**z == x**(y*z)
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list