How does python interpret numbers with leading zeroes

I'm new with python, I'm using python 2.7 when I typed this on python shell:

print 01
print 010
print 0100
print 01000

It gives this result

1
8
64
512

I tried to understand why it gave that but unfortunately I didn't get the point.


If a number starts with 0, it is interpreted as octal, or base 8. Just do:

print 1
print 10
print 100
print 1000

And your problem will be solved.

More on octal: http://en.wikipedia.org/wiki/Octal

Here is a way to understand octal easier:

octal 1 is decimal (normal numbers) 1

octal 2 : decimal 2

...

octal 7 : decimal 7

octal 10: decimal 8

octal 11: decimal 9

octal 12: decimal 10

...

octal 17: decimal 15

octal 20: decimal 16

and so on. Octal just uses digits from 0 to 7.

Hope this helped!


Python interprets a number starting with 0 as octal which is base 8.You can work out the base using the binary string 10 as b^1 === b where b is the base.

# print the decimal value of the binary number 10
>>> print 0b10
2
# print the decimal value of the octal number 10    
>>> print 010
8
# print the decimal value of the hexadecimal number 10
>>> print 0x10
16

In any base the symbol 1 is always the decimal value 1 because b^0 === 1 for all b as reading right to left the index of a number starts at 0.

# print the decimal value of the binary number 1
>>> print 0b001
1
# print the decimal value of the octal number 1
>>> print 0001
1
# print the decimal value of the hexadecimal number 1
>>> print 0x001
1

Once the base is interpreted (0,0b,0x) leading 0 aren't important.

The number of symbols needed for a base is b where the largest symbols is equal to b-1

            Base (b)   Number of Symbols (b)    Symbols (0 : b-1)
Binary      2          2                        0,1
Octal       8          8                        0,1,2,3,4,5,7,6,7
Decimal     10         10                       0,1,2,3,4,5,7,6,7,8,9

The largest value that can be represented by a number is (b^n)-1 where n is the number of digits. Given a 3 digit number the largest decimal value is (10^3)-1 = 999, in octal (8^3)-1 = 511 (decimal) which is 777 in base 8 and in binary (2^3)-1 = 7 (decimal) which is 111 in base 2. So you can see that with less symbols (a lower base) the value you can represent decreases given a fixed number of digits.