问题描述
由于Python 3中的八进制前缀现在是 0
,因此再写 0777
是不合法的。好的。
那么为什么写 00
合理地评估 0
而其他数字会触发语法错误?
>>> 01
...
文件<互动输入>,第1行
01
^
语法错误:无效令牌
>>> ;
>>> 00
0
如果有人看看在(整数)文字部分)页面:
所以这意味着他们为零做了一个例外(在可以找到那里):你可以将零写为零序列。我的猜测当然是他们必须包含0
(你怎么指定零作为 decinteger
? ),那么为什么在这种情况下不允许更多的零,无论数字系统如何, 000
都保持为零。他们可能不希望允许 01
作为 decinteger
来防止意外运行代码,从而获得完全不同的结果。
最后请注意,下划线只是该规范的一部分,因为的问题:在它们在语法中没有提到。
在 指定零后跟其他数字(也是其他零作为 octinteger
:
Since the octal prefix is now 0o
in Python 3 it's not legal to write 0777
any more. Okay.
So why is it legal to write 00
which evaluates properly to 0
whereas other digits trigger a syntax error?
>>> 01
...
File "<interactive input>", line 1
01
^
SyntaxError: invalid token
>>>
>>> 00
0
If one takes a look at the Lexical Analysis (Integer Literal Section) page:
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:
So it means they make an exception for zero (in all documentation for python-3.3 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 python-2.x code and thus obtaining totally different results.
Finally note that the underscores are only part of that specification since python-3.6: in the specifications for 3.5 they are not mentioned in the grammar.
In python-2.7 the documentation specifies a zero followed by other digits (also other zeros as an octinteger
:
这篇关于为什么000在Python 3中评估为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!