为什么有时候关键词前后可以省略空格?例如,为什么表达式2if-1e1else 1
有效?
似乎在CPython 2.7和3.3中都有效:
$ python2
Python 2.7.3 (default, Nov 12 2012, 09:50:25)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2if-1e1else 1
2
$ python3
Python 3.3.0 (default, Nov 12 2012, 10:01:55)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2if-1e1else 1
2
即使在派比:
$ pypy
Python 2.7.2 (341e1e3821ff, Jun 07 2012, 15:42:54)
[PyPy 1.9.0 with GCC 4.2.1] on darwin
Type "help", "copyright", "credits" or "license" for more information.
And now for something completely different: ``PyPy 1.6 released!''
>>>> 2if-1e1else 1
2
最佳答案
python中的标识符描述为:
identifier ::= (letter|"_") (letter | digit | "_")*
因此,
2if
不能是标识符,因此if must be2
,if
。类似的逻辑也适用于表达式的其余部分。基本上解释
2if-1e1else 1
是这样的(完整的解析过程非常复杂):2if
无效标识符,2
匹配数字digit ::= "0"..."9"
,if
匹配关键字。-1e1else
,-1
是:(u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr
的一元否定(1
),它与intpart
中的匹配,
exponentfloat ::= (intpart | pointfloat) | exponent
is exponente1
)您可以看到形式exponent ::= ("e" | "E") ["+" | "-"] digit+
的表达式产生了一个float,它来自:>>> type(2e3)
<type 'float'>
然后,
Ne+|-x
被视为关键字,else
等。您可以阅读gammar了解更多信息。
关于python - 为什么Python总是不需要关键字空格?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16535440/