2017-10-06 56 views
-3

我有這行代碼「如果」在python語句來檢查,如果一個變量是真實的,但其他都是假的

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

當這個運行沒有發生,是有辦法有在一部分如果陳述是真實的但其他的假?

+0

你的意思是'如果SetNum,而不是(SetChar或SETUP或SetLow)'? – khelwood

+0

不要使用'== True'或'== False',這在布爾測試中是不需要的。 –

+0

@khelwood這不適用於python 2.7; 3.x是新功能嗎? – Vinny

回答

2

在Python,if variable檢查truthness做這個測試。這意味着您可以編寫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

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") 
0

我認爲你對的理解是錯誤的。 不會在這裏級聯您的變量的值,即,當您編寫SetChar和SetUp和Setlow == False時,它不會檢查每個變量值是否爲false,它僅檢查這個值是否爲SetLow。由於如果檢查真實性,在您的聲明中,您正在檢查SetChar和SetUp是否爲真,這不是您打算執行的操作。 確保如果兩邊的條件都滿足(條件1 條件2),那麼只需執行下一個語句塊即可。

你只需要使用:

if SetNum and not (SetChar or SetUp or SetLow):