Question

I am new to Python, in a way new to programming.

Was trying to teach myself python from the basics... and came across this weird thing...

Please find below the printing results...

>>> print 1,000,000
1 0 0
>>> print 1,112,231
1 112 231
>>> print 000
0
>>> print 1,001,002
1 1 2
>>> print 1,100,001,0010
1 100 1 8

While I do understand that 0010 is the binary equivalent of 8 (in the last one), I do not understand why does Python do so? Is it some embedded logic of the language or something else?

The remaining, I was able to figure out; however if anyone can give a brief explanation it would be great!

Was it helpful?

Solution 2

Python literals preceded by '0' tells it to express in in octal. literals preceded by '0x' are hexadecimal. literals preceded by '0b' are binary.

print 0010
8

print 0b110011
51

print 0x100
256

I have also tested the '0o' on my python 2.7.6 and gotten

print 0o111 # number 0 letter o followed by digits
73

Note that Python 3 will print 0111 as 111 as it is supposed to treat a leading 0 as part of the decimal number unless it is followed by 'x', 'o', or 'b' I do not have Python 3 so I cannot test this myself.

Thanks to @AdamSmith for pointing this out in his comment.

OTHER TIPS

As said in the comment:

When you start a number by 0 in Python, it assumes it's an Octal number. See this question: What do numbers starting with 0 mean in python?

So what you're seeing in the last case is the decimal representation of the octal 10, which is 8 in decimal:

0010 --> 0*8^2 + 1*8^1 + 0*8^0

If you do print 0111 you'll see 73, because it's 1*8^2 + 1*8^1 + 1*8^0 (64 + 8 + 1)

The print 000 is still printing the decimal representation of the octal 000, but zero in base 8 is the same as 0 in base 10.

EDIT: Thanks to @AdamSmith for pointing the new behavior in Python 3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top