python - 即使没有关键字 `1 < 2`, bool 运算中的 `not_test` 也是 `not` 吗?

标签 python syntax grammar lexical

我正在阅读 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解释如下:

A vertical bar (|) is used to separate alternatives; it is the least binding operator in this notation.

问题来了:

  1. not_test ::= comparison | "not" not_test解析为

    not_test ::= comparison | ("not" not_test) ?

  2. 如果 1.是真的,一个有效的 comparison也是有效的 not_test .(例如 1 < 2 是一个 not_test,即使其中没​​有 not。)

  3. 另外,因为一个有效的and_test可以只是一个有效的 not_test , 1 < 2是有效的 and_test以及。 or_test 也是如此.

  4. 那么什么是有效的comparison1 < 2显然符合模式。这些按位比较表达式同样有效 comparison .共同点是需要至少一个运算符('>'、'<' 或按位的东西)的存在。 (我不确定。)

  5. 奇怪的部分来了。考虑 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 .

但我不明白34可以有效comparison . 我哪里出错了?

最佳答案

“*”表示包含序列的零个或多个实例。 比较 需要运算符,如通过 shift_expr 跟踪到 primary 所示,atom,然后是 literal

关于python - 即使没有关键字 `1 < 2`, bool 运算中的 `not_test` 也是 `not` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22059415/

相关文章:

python - OpenCV Python 链接器错误

syntax - Lucene 全选查询

windows - 无法获得工作的符号链接(symbolic link)(Windows 7)cmd

java - 尝试让 ANTLR 语法遵循 AND/OR 语句

python - 删除 *a : can't use starred expression here

python - 如何通过在 numpy 中广播来防止添加两个数组?

python - 无法在 Android 上的 pygame 中打开图像

python - 为什么在这个列表推导中需要这个列表切片?

android.database.sqlite.SQLiteException : near "ON": syntax error (code 1):

java - 执行由 Jasmin 生成的文件 .classes 时出错