为什么 000 在 Python 3 中计算为 0?

Why does 000 evaluate to 0 in Python 3?

因为八进制前缀现在是 Python 中的 0o 3 所以写 0777 是不合法的。好的

那么为什么写 00 是合法的,它的计算结果是 0 而其他数字会触发语法错误?

>>> 01
  ...
  File "<interactive input>", line 1
    01
     ^
SyntaxError: invalid token
>>> 
>>> 00
0

如果看一看 Lexical Analysis(整数文字部分)页面:

integer      ::=  decinteger | bininteger | octinteger | hexinteger
decinteger   ::=  nonzerodigit (["_"] digit)* | <b>"0"+(["_"] "0")*</b>
...

所以这意味着 decinteger 要么以非零数字开头(后跟所有可能的数字和可选的下划线),要么是一个 零序列 可选下划线(映射到零)。

文档还指出:

Note that leading zeros in a non-zero decimal number are not allowed.

所以这意味着他们对零进行了例外处理(在 one can find there): you can write zero as a sequence of zeros. My guess is that of course they have to include "0" (how else would you specify zero as a decinteger?), so why not allow more zeros in that case, regardless of the number system, 000 is and stays zero. They probably do not want to allow 01 as a decinteger to prevent accidentally running 代码的所有文档中,因此获得了完全不同的结果。

最后请注意,下划线只是该规范的一部分,因为 : in the specifications for 3.5 它们没有在语法中提及。

the documentation 中指定一个零后跟其他数字(还有其他零作为 octinteger:

integer        ::=  decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::=  nonzerodigit digit* | "0"
octinteger     ::=  "0" ("o" | "O") octdigit+ | "0" octdigit+