给定两个“if”语句,如果它们都没有执行,则执行一些代码

2024-06-28 19:28:30 发布

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

嘿,我不知道如何编程这个星座:

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")

只有当这两个条件不成立时,它才应该转到“else”。但如果两个子字符串都包含在字符串中,则应该同时打印这两个子字符串。你知道吗


Tags: and字符串instringifisdef编程
3条回答

另一种选择是使用一个只有在满足条件时才为真的变量。这个变量(我们称之为found)默认为false:

found = False

但是,在每个if语句中,我们将其设置为True

if "abc" in string:
    print ("abc is in string")
    found = True

if "def" in string:
    print ("def is in string")
    found = True

现在我们只需要检查变量。如果满足任何条件,则为真:

if not found:
    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")

我想展示另一种方法。优点是它将代码分为两个逻辑步骤。然而,在像这个例子这样的简单情况下,这个问题可能不值得付出额外的努力。你知道吗

这两个步骤是:1。获得全部部分结果。全部处理

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

相关问题 更多 >