"如果" python中的语句,用于检查一个变量是否为true但其他变量是否为false

时间:2017-10-06 10:14:32

标签: python python-3.x

我有这行代码

if (SetNum == True) and SetChar and SetUp and SetLow == False:
   print("Your password contains", PassNum, "numbers")

当运行时没有任何事情发生,有没有办法让if语句中的一个部分为true而其他部分为false?

2 个答案:

答案 0 :(得分:2)

在Python中,if variable检查真相。这意味着您可以编写if SetNum,它的执行方式与if SetNum == True相同。

但这只是一种更易读的方式;你的问题是你误解了AND的工作原理。

if (SetNum == True) and SetChar and SetUp and SetLow == False:这会打破SetNum == TrueSetChar,这会转化为真值表达。所以如果它是真的,它会继续。下一个是SetUp,与SetChar一样对待。基本上,您只评估最后一项SetLow == False

考虑一下,我认为这更具可读性

if SetNum:
    if not any(SetChar, SetUp, SetLow):
    ...

any - Return True if bool(x) is True for any values x in the iterable.它将验证每个变量,如果它们都是False,它将返回Falsenot语句会将其替换为True

答案 1 :(得分:0)

您可以通过多种方式进行此测试

if (SetNum, SetChar, SetUp, SetLow) == (True, False, False, False):
   print("Your password contains", PassNum, "numbers")

if SetNum and not SetChar and not SetUp and not SetLow:
   print("Your password contains", PassNum, "numbers")