I just executed the following program on my python interpreter:
>>> def mylife(x):
... if x>0:
... print(x)
... else:
... print(-x)
...
>>> mylife(01)
File "<stdin>", line 1
mylife(01)
^
SyntaxError: invalid token
>>> mylife(1)
1
>>> mylife(-1)
1
>>> mylife(0)
0
Now, I have seen this but as the link says, the 0 for octal does not work any more in python (i.e. does not work in python3). But does that not mean that the the behaviour for numbers starting with 0 should be interpreted properly? Either in base-2 or in normal base-10 representation? Since it is not so, why does python behave like that? Is it an implementation issue? Or is it a semantic issue?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
My guess is that since 012 is no longer an octal literal constant in python3.x, they disallowed the 012 syntax to avoid strange backward compatibility bugs. Consider your python2.x script which using octal literal constants:
a = 012 + 013
Then you port it to python 3 and it still works — It just gives you a = 25 instead of a = 21 as you expected previously (decimal). Have fun tracking down that bug.
Method 2
From the Python 3 release notes http://docs.python.org/3.0/whatsnew/3.0.html#integers
Octal literals are no longer of the form
0720; use0o720instead.
The ‘leading zero’ syntax for octal literals in Python 2.x was a common gotcha:
Python 2.7.3 >>> 010 8
In Python 3.x it’s a syntax error, as you’ve discovered:
Python 3.3.0
>>> 010
File "<stdin>", line 1
010
^
SyntaxError: invalid token
You can still convert from strings with leading zeros same as ever:
>>> int("010")
10
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0