2013-04-28 69 views
2

我在檢查變量是true還是false後無法打印消息。我想要做的是打印出變量選擇的變量。必須有一個比以下更簡單的方法,但這是我能想到的。我需要一個更好的解決方案或對下面的修改,使其工作。如果不同的變量是True或False,打印Python 3.3

這裏是我的代碼:

if (quirk) and not (minor, creator, nature): 
    print (quirk, item) 
elif (minor) and not (quirk, creator, nature): 
    print (minor, item) 
elif (creator) and not (minor, quirk, nature): 
    print (creator, item) 
elif (nature) and not (minor, quirk, creator): 
    print (item, nature) 
else: 
    print ("Something went wrong! Properties out of range! Nature =",nature,"Quirk =",quirk,"Minor =",minor,"Creator =",creator) 

在這種情況下,我總是得到錯誤,從來沒有打印任何。該錯誤總是表明其中一個變量是真實的。

預先感謝您!

回答

10

你正在檢查一個非空元組是否是真的 - 這從來都不是真的。改爲使用any

if quirk and not any([minor, creator, nature]): 
    print (quirk, item) 
# and so on 

any([minor, creator, nature])回報True如果任何集合中的元素都是TrueFalse否則。

+0

這完全成功了!當系統允許我時,我會接受安塞爾。謝謝!我想我需要閱讀'任何'。 – Simkill 2013-04-28 11:52:27

+0

@Simkill當你在它的時候,你可能也想閱讀['all'](http://docs.python.org/2/library/functions.html#all),這是一個密切相關的功能。 – Volatility 2013-04-28 11:53:13

5
(minor, creator, nature) 

是一個元組。並且它始終在布爾上下文中計算爲True,而不考慮minorcreatornature的值。

這就是documentation for Truth Value Testing不得不說:

任何對象都可以對真值進行測試,在使用if或while 條件或以下布爾運算的操作數。下面 值被認爲是假:

  • 任何數值類型的零,例如,0,0.0,0j的。
  • 任何空序列,例如'',(),[]。
  • 任何空映射,例如{}。一個布爾()用戶定義的類的
  • 情況下,如果類定義或len個()方法中,當該方法返回整數零或布爾值假。

所有其他值都被認爲是真的 - 因此許多類型的對象總是爲真。

你非空序列落入「所有其他值」類等被認爲是真實的。


要使用普通的Python邏輯表達你的條件,你需要寫:

if quirk and not minor and not creator and not nature: 

由於@Volatility指出,any()效用函數可以用來簡化代碼,使其瞭解更多清晰。

1

any感覺就像矯枉過正這裏:

if quirk and not (minor or creator or nature): 
    print (quirk, item) 
elif minor and not (quirk or creator or nature): 
    print (minor, item) 
elif creator and not (minor or quirk or nature): 
    print (creator, item) 
elif nature and not (minor or quirk or creator): 
    print (item, nature) 
else: 
    print ("Something went wrong! Properties out of range! Nature =",nature,"Quirk =",quirk,"Minor =",minor,"Creator =",creator)