逻辑语句的优先级NOT AND&在python中

Aks*_*pta 67 python boolean-expression python-3.x

据我所知,在C&C++中,NOT AND&OR的优先顺序是NOT> AND> OR.但这似乎在Python中没有类似的方式.我尝试在Python文档中搜索它并失败(猜猜我有点不耐烦.).有人可以为我清除这个吗?

Kyl*_*ton 71

根据文档https://docs.python.org/3/reference/expressions.html#operator-precedence,它不是,也不是,从最高到最低

这是完整的优先级表,最高的优先级.一行具有相同的优先级,从左到右具有链

  1. 拉姆达
  2. 如果别的
  3. 要么
  4. 不是x
  5. in,not in,is,not not,<,<=,>,> =,!=,==
  6. |
  7. ^
  8. &
  9. <<,>>
  10. +, -
  11. *,/,//,%
  12. + x,-x,~x
  13. **
  14. x [index],x [index:index],x(arguments ...),x.attribute
  15. (表达式......),[表达式...],{键:值...},{表达式...}

编辑:有错误的优先权

  • 请注意,当涉及到算术运算符的优先级时,“**”在脚注中注明了一些例外情况。 (2认同)

nos*_*nos 19

您可以执行以下测试来确定and和的优先级or.

首先,尝试0 and 0 or 1在python控制台中

如果or先绑定,那么我们期望0作为输出.

在我的控制台中,1是输出.它意味着and要么先绑定要么等于or(可能是从左到右计算表达式).

然后试试1 or 0 and 0.

如果or并且and与内置的从左到右的评估顺序同等绑定,那么我们应该得到0输出.

在我的控制台中,1是输出.然后我们可以得出结论,and它的优先级高于or.

  • 更明确地说,表达式的计算结果为:“((0 and 0) or 1)”和“(1 or (0 and 0))” (4认同)
  • 然而,在第二个表达式中,如果“exp1”为“True”,则“(0 and 0)”永远不会被计算为“(exp1 or exp2)”,直接返回。类似地,在第一个表达式中,“and 0”部分永远不会被计算,因为如果“exp1”为“False”,则“exp1”和“exp2”直接返回。 (2认同)

mgi*_*son 17

not语言参考中所述的更紧密地and束缚or


Osw*_*irt 6

布尔运算符的优先级,从最弱到最强,如下:

  1. or
  2. and
  3. not x
  4. is not; not in

如果运算符具有同等优先级,则从左到右进行评估。


Vic*_*art 6

一些简单的例子;注意运算符优先级(not、and、or);括号以帮助人类解释。

a = 'apple'
b = 'banana'
c = 'carrots'

if c == 'carrots' and a == 'apple' and b == 'BELGIUM':
    print('True')
else:
    print('False')
# False
Run Code Online (Sandbox Code Playgroud)

相似地:

if b == 'banana'
True

if c == 'CANADA' and a == 'apple'
False

if c == 'CANADA' or a == 'apple'
True

if c == 'carrots' and a == 'apple' or b == 'BELGIUM'
True

# Note this one, which might surprise you:
if c == 'CANADA' and a == 'apple' or b == 'banana'
True

# ... it is the same as:
if (c == 'CANADA' and a == 'apple') or b == 'banana':
True

if c == 'CANADA' and (a == 'apple' or b == 'banana'):
False

if c == 'CANADA' and a == 'apple' or b == 'BELGIUM'
False

if c == 'CANADA' or a == 'apple' and b == 'banana'
True

if c == 'CANADA' or (a == 'apple' and b == 'banana')
True

if (c == 'carrots' and a == 'apple') or b == 'BELGIUM'
True

if c == 'carrots' and (a == 'apple' or b == 'BELGIUM')
True

if a == 'apple' and b == 'banana' or c == 'CANADA'
True

if (a == 'apple' and b == 'banana') or c == 'CANADA'
True

if a == 'apple' and (b == 'banana' or c == 'CANADA')
True

if a == 'apple' and (b == 'banana' and c == 'CANADA')
False

if a == 'apple' or (b == 'banana' and c == 'CANADA')
True
Run Code Online (Sandbox Code Playgroud)