What do numbers starting with 0 mean in python?

Viewed 79021

When I type small integers with a 0 in front into python, they give weird results. Why is this?

>>> 011
9
>>> 0100
64
>>> 027
23

I'm using Python 2.7.3. I have tested this in Python 3.0, and apparently this is now an error. So it is something version-specific.

They are apparently still integers:

>>> type(027)
<type 'int'>
9 Answers

I have tried it out. I have learned a little bit. From Java I know this as a pitfall: A leading zero introduces an octal number. I have colleagues which didn't resp. don't know that after more than years with experience in Java.

Now I was interesting what the behaviour in Python is. I appreciate that change from Python 2 to Python 3. It is pitfall I have never understood why Java (a young language with focus on "beeing easy") could take over that stupid solution from C.

A leading zero as prefix can be accidentally typed (bad solution). 0x for a hexadecimal number is never accidentally typed (good solution). But 0 and o are to similar therefore I think 0o23 in Python is not a perfect solution. 0c23 (octal) would be a better solution in my opinion.

The latest Python specification for number literals is in PEP-3127 "Integer Literal Support and Syntax"

The syntax for 011 has been removed in Python 3.0. The syntax for 0o11 has been added in Python 2.6 and it is the only one supported after Python 3.0. There is no __future__ import in Python 2 that would disallow or atleast warn on number literals with leading zeros, so developers have to know what 011 means and that it should be avoided (and that it can actually be avoided).

Related