我正在阅读 Python 文档 2.76
This is the lexical syntax of the 3 kinds of boolean operations :
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
This is the lexical syntax for comparision :
comparison ::= or_expr ( comp_operator or_expr )*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
| "is" ["not"] | ["not"] "in"
and the lexical syntax for or_expr :
and_expr ::= shift_expr | and_expr "&" shift_expr
xor_expr ::= and_expr | xor_expr "^" and_expr
or_expr ::= xor_expr | or_expr "|" xor_expr
文档中的Notation解释如下:
问题来了:
是
not_test ::= comparison | "not" not_test
解析为not_test ::= comparison | ("not" not_test)
?如果
1.
是真的,一个有效的comparison
也是有效的not_test
.(例如1 < 2
是一个not_test
,即使其中没有not
。)另外,因为一个有效的
and_test
可以只是一个有效的not_test
,1 < 2
是有效的and_test
以及。or_test
也是如此.那么什么是有效的
comparison
?1 < 2
显然符合模式。这些按位比较表达式同样有效comparison
.共同点是需要至少一个运算符('>'、'<' 或按位的东西)的存在。 (我不确定。)奇怪的部分来了。考虑
x and y
例如。根据
and_test ::= not_test | and_test "and" not_test
and_test ::= not_test | (and_test "and" not_test)
# 我相信这样解析?
如果 x and y
是真的是有效的 and_test
(它永远不会是 not_test
因为 and
的存在),那么 x
必须是有效的 and_test
这只能是一个有效的 not_test
.和 y
必须是有效的 not_test
也。
A not_test
可以是单个 comparison
或另一个 not_test
前面是 not
.所以一个not_test
基本上是零个或多个 not
s 后跟一个 comparison
.现在重要的是 comparison
的词法语法.
根据 4.
, 一个 comparison
必须至少有一名运算符(operator)。但这与下面的例子有冲突:
赋值 x = 3, y = 4 。 3 and 4
似乎有效 and_test
.
但我不明白3
或 4
可以有效comparison
.
我哪里出错了?
最佳答案
“*”表示包含序列的零个或多个实例。 比较
不 需要运算符,如通过 shift_expr
跟踪到 primary
所示,atom
,然后是 literal
。
关于python - 即使没有关键字 `1 < 2`, bool 运算中的 `not_test` 也是 `not` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22059415/