我有这行代码
if (SetNum == True) and SetChar and SetUp and SetLow == False:
print("Your password contains", PassNum, "numbers")
当运行时没有任何事情发生,有没有办法让if语句中的一个部分为true而其他部分为false?
答案 0 :(得分:2)
在Python中,if variable
检查真相。这意味着您可以编写if SetNum
,它的执行方式与if SetNum == True
相同。
但这只是一种更易读的方式;你的问题是你误解了AND
的工作原理。
if (SetNum == True) and SetChar and SetUp and SetLow == False:
这会打破SetNum == True
和SetChar
,这会转化为真值表达。所以如果它是真的,它会继续。下一个是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
,它将返回False
。 not
语句会将其替换为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")