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

时间:2013-05-21 20:50:48

标签: python python-3.x boolean-expression

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

6 个答案:

答案 0 :(得分:65)

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

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

  1. 拉姆达
  2. if - else
  3. not x
  4. in,not in,is,is not,<,< =,>,> =,!=,==
  5. |
  6. ^
  7. &安培;
  8. <<,>>
  9. +, -
  10. *,/,//,%
  11. + x,-x,~x
  12. **
  13. x [index],x [index:index],x(arguments ...),x.attribute
  14. (表达式......),[表达式...],{键:值...},{表达式...}
  15. 编辑:错误优先

答案 1 :(得分:16)

notand更紧密,比language reference

中所述的or更紧密。

答案 2 :(得分:16)

您可以执行以下测试来确定andor的优先顺序。

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

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

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

然后尝试1 or 0 and 0

如果orand与内置的左到右评估顺序绑定相同,那么我们应该将0作为输出。

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

答案 3 :(得分:4)

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

  1. or
  2. and
  3. not x
  4. is not; not in
  5. 如果运营商具有相同的优先权,则评估从左到右进行。

答案 4 :(得分:2)

没有充分的理由让Python拥有其他优先顺序的运算符而不是完善的(几乎)所有其他编程语言,包括C / C ++。

您可以在 Python语言参考,第6.16部分 - 运算符优先级,可下载(适用于当前版本并包含所有其他标准文档)的https://docs.python.org/3/download.html中找到它,或者阅读它在线:6.16. Operator precedence

但是Python中还有一些可能误导你的东西:andor运算符的结果可能与{{>不同来自{{ 1}}或True - 请参阅同一文档中的6.11 Boolean operations

答案 5 :(得分:1)

一些简单的例子;注意运算符的优先级(不是,和,或);括号以辅助人类解释。

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

if c == 'carrots' and a == 'apple' and b == 'BELGIUM':
    print('True')
else:
    print('False')
# False

类似地:

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