为什么';Python是否总是要求关键字周围有空格?

为什么';Python是否总是要求关键字周围有空格?,python,pypy,cpython,Python,Pypy,Cpython,为什么关键字前后有时可以省略空格?例如,为什么表达式2if-1else 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"

为什么关键字前后有时可以省略空格?例如,为什么表达式
2if-1else 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中:

$ 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必须是
2
if
。类似的逻辑适用于表达式的其余部分

基本上,解释
2if-1else 1
的过程是这样的(完整的解析将相当复杂):

2如果
标识符无效,
2
匹配数字
数字::=“0”…“9”
如果
匹配关键字。
-1else
-1
1
中与
intpart
中的
intpart
相匹配的
index float:=(intpart | pointfloat)
e1
是指数
指数:=(“e”|“e”)[“+”|“-“]位+
)您可以看到形式为
Ne+|-x的表达式从以下公式中产生浮点:

>>> type(2e3)
<type 'float'>
>>类型(2e3)
然后,
else
被视为关键字,
-1


您可以仔细阅读以了解更多信息。

“…
-1
匹配
intpart
…”等等,什么?
-
不是一元运算符吗?所以基本上是这样的,因为阻止它会使语法/解析器更加复杂。@asmuer是这样的,因为它是语法(如果有意义的话)嗯,是的,但我很确定语法不是自己写的。Python语言的每一个方面都是有原因的。为了额外的乐趣:在表达式中使用
2if
是可以接受的,但使用
2else
则不是;这可能是因为后者被解析为
2e???
,而
是一个非数字,这是一个语法错误