Python Exponent Question
Michael J. Fromberger
Michael.J.Fromberger at Clothing.Dartmouth.EDU
Mon Dec 17 12:08:59 EST 2007
In article
<29b9c1c1-2cdd-4cde-8f2e-82a4bc01e016 at r60g2000hsc.googlegroups.com>,
databyss <databyss at gmail.com> 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
Python's ** operator associates to the right, not to the left; thus,
2 ** 2 ** 2 ** 2
... really means
2 ** (2 ** (2 ** 2))
... and not
((2 ** 2) ** 2) ** 2
... as you seem to expect. As usual, you can enforce different
associations by explicitly including the parentheses.
Cheers,
-M
--
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
More information about the Python-list
mailing list