binary numbers?
I am using the python shell t开发者_C百科o figure out how the print command works in python.
When I type inprint 01
1 print 010 8 print 0100 64 print 030 24
What's going on here? Is it just base 2? Why does the "one" in the second position print as 8? Shouldn't it be 2 if it's binary?
Starting a number with a zero marks it as octal in Python 2. This has been recognized as confusing, surprising and also inconsistent, as starting with 0x will mark it as hexadecimal. Therefore, in Python 3, starting with 0 is invalid, and you get octal by starting with 0o. You can also start with 0b to mark it as binary.
>>> 10
10
>>> 0x10
16
>>> 0o10
8
>>> 0b10
2
>>> 010
File "<stdin>", line 1
010
^
SyntaxError: invalid token
0x, 0o and 0b also works in Python 2.6 and Python 2.7.
That's the old notation for octal numbers in Python.
In Python 2.6 and newer you should use the syntax 0o10
for octal and 0b10010
for binary numbers.
In older versions of Python you enter binary numbers as strings and parse them to integers:
>>> x = int("10010", 2)
>>> print x
18
Preceding an integer literal with 0
marks it as octal.
This has changed in Python 3 and is not recommended from Python 2.6 onwards: use 0o...
instead.
>>> 0b1010 == 012 == 0xA == 10
True
When you append 0 to the left of the number, it is interpreted as an octal number. So 10 in octal equals 8 in decimal, and 100 in octal equals 64 in decimal and so on.
If you want to deal with binary number, you should use bit-wise operators to play with the bits.
Like in most programming languages, Python follows the C tradition of numbers starting with 0 being octal (base 8) numbers.
It's interpreting them as octal (base 8) numbers, not binary.
Definitely not base2. It's Octal - base 8.
Numbers starting with 0 are interpreted as octal. For binary numbers the 'start sequence' is 0b.
>>> print 0b10
2
>>> print 010
8
>>> print 0x10
16
精彩评论