为什么000在Python 3中评估为0? [英] Why does 000 evaluate to 0 in Python 3?

查看:282
本文介绍了为什么000在Python 3中评估为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Python 3中的八进制前缀现在是 0 ,因此再写 0777 是不合法的。好的。



那么为什么写 00 合理地评估 0 而其他数字会触发语法错误?

 >>> 01 
...
文件<互动输入>,第1行
01
^
语法错误:无效令牌
>>> ;
>>> 00
0


解决方案

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


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




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



该文档还声明:


请注意,非零十进制数中的前导零允许。


所以这意味着他们为零做了一个例外(在 python-3.3 可以找到那里):你可以将零写为零序列。我的猜测当然是他们必须包含0(你怎么指定零作为 decinteger ? ),那么为什么在这种情况下不允许更多的零,无论数字系统如何, 000 都保持为零。他们可能不希望允许 01 作为 decinteger 来防止意外运行 python-2.x 代码,从而获得完全不同的结果。



最后请注意,下划线只是该规范的一部分,因为 python-3.6 的问题:在 3.5的规范它们在语法中没有提到。



python-2.7 文档指定零后跟其他数字(也是其他零作为 octinteger


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



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:

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+

这篇关于为什么000在Python 3中评估为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆