如果不同变量为真或假python3.3,则打印

2024-05-23 15:07:06 发布

您现在位置:Python中文网/ 问答频道 /正文

在检查变量是否为真或假后,我无法打印消息。我要做的是打印出一系列变量中为真的变量。一定有比下面更简单的方法,但这是我能想到的。我需要一个更好的解决方案或修改下面的工作。在

这是我的代码:

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)

在这种情况下,我总是得到错误,从来没有任何指纹。错误总是显示其中一个变量是真的。在

提前谢谢你!在


Tags: and方法代码if错误not解决方案item
3条回答

你正在检查一个非空元组是否是falsish-这永远不是真的。请改用^{}。在

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

any([minor, creator, nature])如果集合中有任何元素是True,则返回{},否则返回{}。在

(minor, creator, nature)

是元组。它总是在布尔上下文中求值为True,而不管minorcreator和{}的值。在

这是documentation for Truth Value Testing要说的:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a bool() or len() method, when that method returns the integer zero or bool value False.

All other values are considered true — so objects of many types are always true.

您的非空序列属于“所有其他值”类别,因此被认为是真的。在


要使用纯Python逻辑表示条件,需要编写:

^{pr2}$

正如@volatile指出的,any()实用函数可以用来简化代码并使其读得更清楚。在

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)

相关问题 更多 >