Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

python - binary numbers?

I am using the python shell to figure out how the print command works in python.
When I type in

print 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...