Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do numbers starting with 0 mean in python?

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'> 
like image 911
Rob Volgman Avatar asked Jul 23 '12 20:07

Rob Volgman


People also ask

Can an integer start with 0 Python?

Python 3 drops the 0 prefix: integer literals that start with 0 are illegal (except zero itself, and 0x / 0o / 0b prefixes).

Is 0 a float or int Python?

Introduction to integersEdit An integer, commonly abbreviated to int, is a whole number (positive, negative, or zero). So 7 , 0 , -11 , 2 , and 5 are integers. 3.14159 , 0.0001 , 11.11111 , and even 2.0 are not integers, they are floats in Python.

What is an 0o prefix in Python?

Number having 0o or 0O as prefix represents octal number which can have 0 to 7 as one of the digits in it. Example: 0O12: equivalent to 10 (ten) in decimal number system. Number with 0x or 0X as prefix represents hexadecimal number.

Why do we use 0 in Python?

In Python, you cannot "set" a value to zero, because zero is the value, and it is immutable. By saying x = 0 you remove the name x from whatever it was before and attach it to the number zero instead. There was a good talk about this topic at this year's PyCon. It is available on Youtube.


2 Answers

These are numbers represented in base 8 (octal numbers). Some examples:

Python 2 (old format)

Note: these forms only work on Python 2.x.

011 is equal to 1⋅8¹ + 1⋅8⁰ = 9,

0100 is equal to 1⋅8² + 0⋅8¹ + 0⋅8⁰ = 64,

027 is equal to 2⋅8¹ + 7⋅8⁰ = 16 + 7 = 23.

Python 3 (new format)

In Python 3, one must use 0o instead of just 0 to indicate an octal constant, e.g. 0o11 or 0o27, etc. Python 2.x versions >= 2.6 supports both the new and the old format.

0o11 is equal to 1⋅8¹ + 1⋅8⁰ = 9,

0o100 is equal to 1⋅8² + 0⋅8¹ + 0⋅8⁰ = 64,

0o27 is equal to 2⋅8¹ + 7⋅8⁰ = 16 + 7 = 23.

like image 192
unutbu Avatar answered Oct 12 '22 23:10

unutbu


In Python 2 (and a few more programming languages), these represent octal numbers.

In Python 3, 011 no longer works and you would use 0o11 instead.

In response to edit: and they are regular integers. They are just specified different way; and they are automatically converted by Python to an internal integer representation (which is base-2 actually, so both 9 and 011 are internally converted to 0b1001).

like image 28
Michał Górny Avatar answered Oct 13 '22 00:10

Michał Górny