string = " "
if "abc" in string:
print ("abc is in string")
if "def" in string:
print ("def is in string")
else:
print ("abc and def are not contained in string")
abc = "abc" in string
def_ = "def" in string
if abc :
print("abc in string")
if def_ :
print("def in string")
if not (abc or def_) :
print("neither abc nor def are in this string")
DEFAULT = ["abc and def are not contained in string"]
string = "..."
msglist = []
if "abc" in string:
msglist.append("abc is in string")
if "def" in string:
msglist.append("def is in string")
# more tests could be added here
msglist = msglist or DEFAULT
for msg in msglist:
print(msg)
# more processing could be added here
另一种选择是使用一个只有在满足条件时才为真的变量。这个变量(我们称之为
found
)默认为false:但是,在每个
if
语句中,我们将其设置为True
:现在我们只需要检查变量。如果满足任何条件,则为真:
这只是解决这个问题的方法之一,但我已经见过很多次使用这种模式。当然,你可以选择其他方法,如果你觉得它会更好。你知道吗
您可以简单地为每个条件定义一个布尔值 它使代码保持简单
我想展示另一种方法。优点是它将代码分为两个逻辑步骤。然而,在像这个例子这样的简单情况下,这个问题可能不值得付出额外的努力。你知道吗
这两个步骤是:1。获得全部部分结果。全部处理
相关问题 更多 >
编程相关推荐