Why does 000 evaluate to 0 in Python 3?

落花浮王杯 提交于 2019-11-29 05:40:36

If one takes a look at the Lexical Analysis (Integer Literal Section) page:

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

So that means that a decinteger either begins with a nonzero digit (followed by all possible digits and optionally underscores), or is a sequence of zeros with optionally underscores (which maps to zero).

The documentation furthermore states that:

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

So it means they make an exception for zero (in all documentation for 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 code and thus obtaining totally different results.

Finally note that the underscores are only part of that specification since : in the specifications for 3.5 they are not mentioned in the grammar.

In the documentation specifies a zero followed by other digits (also other zeros as an octinteger:

integer        ::=  decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::=  nonzerodigit digit* | "0"
octinteger     ::=  "0" ("o" | "O") octdigit+ | "0" octdigit+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!