我有一个脚本,它通过 if 语句检查 bool 值,然后执行代码。我想做的是:
if variable a is True, check if b is True and execute code
if variable a is False, execute the same code mentioned before
我目前拥有的简化版本是这样的:
if a:
if b:
print('foo')
else:
print('foo')
有没有更好的方法不需要我编写 print('foo')
两次?
最佳答案
if not a or (a and b):
print('foo')
让我们一步步来谈谈这个:
print('foo')
什么时候执行?
- 当
a
和b
都为True
时。 else
执行时,else
是什么?与前面的if
相反,所以not a
。
最后,您希望在一种情况下显示 'foo'
。
编辑:或者,通过简化逻辑方程:
注意: 除非您知道自己在做什么,否则您可能希望避免这种情况!清晰通常比简短好得多。相信我的建议!我去过那里! ;)
if not a or b:
print('foo')
因为如果not a
不是True
,那么a
一定是True
(的第二部分code>or
),所以 a 和 b
可以简化为 b
(因为我们确实知道 a
在这种情况下为 True
,因此 a and b
与 True and b
相同,因此我们可以安全地删除第一部分)。
关于Python:如果第一个变量为真,则检查第二个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29180754/