Python:如果第一个变量为True,则检查第二个变量?
我有一个脚本,它通过if语句检查bools,然后执行代码。我想做的是使其:Python:如果第一个变量为True,则检查第二个变量?,python,if-statement,python-3.x,Python,If Statement,Python 3.x,我有一个脚本,它通过if语句检查bools,然后执行代码。我想做的是使其: 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') 有没有更好的方法不需要我写
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
so非a
相反'foo'
编辑:或者,通过简化逻辑方程:
注意:除非您知道自己在做什么,否则您可能希望避免这样做!清晰往往比简短好得多。相信我的建议!我经历过那里!;)
因为如果
nota
不是True
,那么a
必须是True
(或的第二部分),所以a和b
可以简化为b
(因为我们确实知道,在这种情况下,a
是True
,所以a和b
与True和b
相同,所以我们可以安全地放下第一部分)。虽然杰罗姆的答案是正确的,但另一种选择是:
print("foo" if ((not a) or (a and b)) else '')
如果不打印“foo”,它将打印一个空行
如果您不想发生这种情况,可以这样利用它:
print("foo") if ((not a) or (a and b)) else ''
”
或其他任何东西都可以使用,因为它们会在自然界中被丢弃。你也可以阅读更多关于为什么,-a⋁(一)⋀(b)≣——a⋀b
,通过学习,和。谢谢!逻辑非常简单,所以我可能不会有任何问题,但我会小心的不,不会。如果条件不满足,它不会做任何事情。我甚至会说你这样做的方式是滥用if…else
表达式。ITYM打印(“foo”if((不是a)或(a和b))else“”)
相反。。。
print("foo") if ((not a) or (a and b)) else ''