gpt4 book ai didi

python - 为什么 Python 不总是要求关键字周围有空格?

转载 作者:太空狗 更新时间:2023-10-29 17:07:20 25 4
gpt4 key购买 nike

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

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

基本上解释 2if-1e1else 1 会是这样的(完整的解析会相当复杂):

2if 不是有效标识符,2 匹配数字 digit::= "0"..."9",if 匹配关键字。-1e1else-1是一元取反(u_expr::= power | "-"u_expr | "+"u_expr | "~"u_expr) : ( 1 匹配 exponentfloat::= (intpart | pointfloat) | exponent 中的 intpart , e1 是指数 exponent::= ("e"| "E") ["+"| "-"] digit+。)您可以看到 Ne+|-x 形式的表达式产生一个 float :

>>> type(2e3)
<type 'float'>

然后else被视为关键字,-1等。

您可以仔细阅读 gammar阅读更多相关信息。

关于python - 为什么 Python 不总是要求关键字周围有空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16535440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com