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,它不是,也不是,从最高到最低
这是完整的优先级表,最高的优先级.一行具有相同的优先级,从左到右具有链
编辑:有错误的优先权
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.
一些简单的例子;注意运算符优先级(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)