2014-03-20

print 0100?

Only start numbers with 0 if the second character is a decimal point!



A few days ago, I saw some Python 2 code looking like this:

expval = date(2011, 03, 02)

Ok, that's harmless, but only because the number was less than 8... Let me show you:

>>> print 02
2
>>> print 03
3
>>> print 07
7
>>> print 08
  File "<stdin>", line 1
    print 08
           ^
SyntaxError: invalid token
>>> print 0100
64
>>> print 100
100

If it wasn't clear to you from the beginning, you probably got it now: Numbers beginning with a 0 are seen as octal number in Python 2. (I.e. base 8 instead of base 10 as the decimal numbers we normally use.) This was probably not Guido's brightest move when he designed Python. He simply copied a common practice in other languages such as C. Prefix 0x always meant hexadeciaml, and later 0b appeared for binary (even though he rejected it when I first asked) and 0o as a saner syntax for octal.

>>> print 0xff
255
>>> print 0b01010
10
>>> print 0b10010
18
>>> print 0o10010
4104
>>> print 0o100
64

In Python 3, 0o ithe the only way to write octal numbers. Literals consisting of digits starting with 0 is a syntax error:

>>> print(0o100)
64
>>> print(0100)
  File "<stdin>", line 1
    print(0100)
             ^
SyntaxError: invalid token

No comments:

Post a Comment