strange math?
Steven Bethard
steven.bethard at gmail.com
Sun Mar 19 00:34:03 EST 2006
joe.hrbek at gmail.com wrote:
>>>> f(01)
> 43
>>>> f(02)
> 44
>>>> f(010)
> 50
>>>> 42+010
> 50
>
> The first f(01) was a mistake. I accidentally forgot to delete the
> zero, but to my suprise, it yielded the result I expected. So, I tried
> it again, and viola, the right answer. So, I decided to really try and
> throw it for a loop, f(010), and it produced 50. I expected 52
> (42+10). Why doesn't python ignore the first zero and produce a result
> of 52? It ignored the first zero for f(01) and f(02). Hmm. I know, I
> know, why am I sending it a 01,02, or a 010 to begin with? Like I
> said, it was an accident, but now i'm curious. I'm not a computer
> science major so please be kind with any explanations.
Python isn't ignoring the initial 0. It reads the initial 0 as
indicating that the following number is expressed in octal. You can see
this if you try any number with a digit higher than 7 in it:
>>> 08
Traceback ( File "<interactive input>", line 1
08
^
SyntaxError: invalid token
So you get 8 added to your number when you write 010 because eight is
spelled as 10 in octal.
The leading-zero notation is unfortunate, and there has been some recent
discussion[1][2] on python-dev about trying to change the prefix to
``0o`` or ``0c`` in Python 3.0 but for the moment at least it looks like
we're stuck with the confusing leading zero.
[1]http://mail.python.org/pipermail/python-dev/2006-January/060262.html
[2]http://mail.python.org/pipermail/python-dev/2006-February/060277.html
STeVe
More information about the Python-list
mailing list