我有這行代碼「如果」在python語句來檢查,如果一個變量是真實的,但其他都是假的
if (SetNum == True) and SetChar and SetUp and SetLow == False:
print("Your password contains", PassNum, "numbers")
當這個運行沒有發生,是有辦法有在一部分如果陳述是真實的但其他的假?
我有這行代碼「如果」在python語句來檢查,如果一個變量是真實的,但其他都是假的
if (SetNum == True) and SetChar and SetUp and SetLow == False:
print("Your password contains", PassNum, "numbers")
當這個運行沒有發生,是有辦法有在一部分如果陳述是真實的但其他的假?
在Python,if variable
檢查truthness做這個測試。這意味着您可以編寫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
。
您可以通過多種方式
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")
我認爲你對和的理解是錯誤的。 和不會在這裏級聯您的變量的值,即,當您編寫SetChar和SetUp和Setlow == False時,它不會檢查每個變量值是否爲false,它僅檢查這個值是否爲SetLow。由於如果檢查真實性,在您的聲明中,您正在檢查SetChar和SetUp是否爲真,這不是您打算執行的操作。 和確保如果兩邊的條件都滿足(條件1 和條件2),那麼只需執行下一個語句塊即可。
你只需要使用:
if SetNum and not (SetChar or SetUp or SetLow):
你的意思是'如果SetNum,而不是(SetChar或SETUP或SetLow)'? – khelwood
不要使用'== True'或'== False',這在布爾測試中是不需要的。 –
@khelwood這不適用於python 2.7; 3.x是新功能嗎? – Vinny