2013-04-28 37 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)