簡體   English   中英

python中的“if”語句,檢查一個變量是否為真,而其他變量是否為假

[英]"if" statement in python that checks if one variable is true but others are false

我有這行代碼

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

當運行時什么都沒有發生,有沒有辦法讓 if 語句中的一部分為真,而其他為假?

在 Python 中, if variable檢查真實性。 這意味着您可以編寫if SetNum並且它的執行方式與if SetNum == True相同。

但這只是一種更具可讀性的方式; 您的問題是您誤解了AND工作原理。

if (SetNum == True) and SetChar and SetUp and SetLow == False:這打破了SetNum == TrueSetChar ,它轉化為真實性表達。 所以如果它是真的,它會繼續。 接下來是SetUp ,與SetChar一樣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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM