理解长布尔表达式的评估

时间:2017-03-01 08:22:04

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

void foo(int* a, size_t n)
{
     if (isShared(a)) {
         // a is known to be in shared memory, 
         // so use it directly
     } else {
         // make a copy of a in shared memory
         // and use the copy
     }
}

这是我们在Python类中学习的逻辑问题。我不明白答案是3,def main(): x = True y = False z = False if not x or y: #False print (1) elif not x or not y and z: #False print (2) elif not x or y or not y and x: #True print (3) else: print (4) main() not x or y or not y and x,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

每当与布尔表达式混淆时,使用括号有助于使评估序列清晰。可以通过跟随the precedence rules和运算符的关联性来放置括号。然后你可以替换并评估结果:

>>> (not x) or y
# not x ==> not False == False
# y == False
# False or False == False

>>> (not x) or ((not y) and z)
# not x == False 
# not y == True
# z == False
# True and z ==> True and False == False
# False or False == False

>>> ((not x) or y) or ((not y) and x)
# Evaluate it yourself

如果您自己评估最后一个示例,则会看到它如何导致False or True产生True,从而允许运行包含它的if语句。