据我所知,在C& C ++,NOT AND&的优先顺序或者不是> AND> OR。但这似乎在Python中没有类似的方式。我尝试在Python文档中搜索它并失败(猜猜我有点不耐烦。)。有人可以帮我解决这个问题吗?
答案 0 :(得分:65)
根据文档,它不是,也不是,从最高到最低 https://docs.python.org/3/reference/expressions.html#operator-precedence
这是完整的优先级表,最高优先级最高。一行具有相同的优先级,从左到右具有链
编辑:错误优先
答案 1 :(得分:16)
not
比and
更紧密,比language reference
or
更紧密。
答案 2 :(得分:16)
您可以执行以下测试来确定and
和or
的优先顺序。
首先,在python控制台中尝试0 and 0 or 1
如果or
首先绑定,那么我们会期望0
作为输出。
在我的控制台中,1
是输出。这意味着and
首先绑定或等于or
(可能是从左到右计算表达式)。
然后尝试1 or 0 and 0
。
如果or
和and
与内置的左到右评估顺序绑定相同,那么我们应该将0
作为输出。
在我的控制台中,1
是输出。然后,我们可以得出结论:and
的优先级高于or
。
答案 3 :(得分:4)
在布尔运算符中,从最弱到最强的优先级如下:
or
and
not x
is not
; not in
如果运营商具有相同的优先权,则评估从左到右进行。
答案 4 :(得分:2)
没有充分的理由让Python拥有其他优先顺序的运算符而不是完善的(几乎)所有其他编程语言,包括C / C ++。
您可以在 Python语言参考,第6.16部分 - 运算符优先级,可下载(适用于当前版本并包含所有其他标准文档)的https://docs.python.org/3/download.html中找到它,或者阅读它在线:6.16. Operator precedence。
但是Python中还有一些可能误导你的东西:and
和or
运算符的结果可能与{{>不同来自{{ 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