繁体   English   中英

如何修复Python Elif?

[英]How to fix a Python elif?

好的,我下面的代码执行了我不希望它执行的操作。 如果您运行该程序,它将询问您“您好吗?”。 (显然),但是当您给出适用于elif语句的问题的答案时,我仍然会得到if语句的响应。 为什么是这样?

talk = raw_input("How are you?")
if "good" or "fine" in talk:
     print "Glad to here it..."
elif "bad" or "sad" or "terrible" in talk:
     print "I'm sorry to hear that!"

问题是or运算符在这里不执行您想要的操作。 您实际上是在说if the value of "good" is True or "fine" is in talk “ good”的值始终为True,因为它是一个非空字符串,因此始终执行该分支。

if "good" in talk or "fine" in talk 您写的内容等同于if "good" or ("fine" in talk)

talk = raw_input("How are you?")
if any(x in talk for x in ("good", "fine")):
     print "Glad to here it..."
elif any(x in talk for x in ("bad", "sad", "terrible")):
     print "I'm sorry to hear that!"

注意:

In [46]: "good" or "fine" in "I'm feeling blue"
Out[46]: 'good'

Python将条件分组如下:

("good") or ("fine" in "I'm feeling blue")

就布尔值而言,这等效于:

True or False

等于

True

这就是为什么if块总是被执行的原因。

使用正则表达式。 如果输入的内容是“我很好,那么我还好。抱歉,我感到糟糕,我不好。” 然后,您将满足所有条件,并且输出将不会达到您的期望。

您必须分别测试每个字符串,或者测试是否包含在列表或元组中。

在您的代码中,Python将获取字符串的值并测试它们的真实性( "good"', “坏”和"sad"' will return True,因为它们不为空),然后它将检查是否对话的字符是“ fine”(因为in运算符使用字符串的方式)。

您应该执行以下操作:

talk = raw_input("How are you?")
if talk in ("good", "fine"):
     print "Glad to here it..."
elif talk in ("bad", "sad", "terrible"):
     print "I'm sorry to hear that!"

这对我有用:

talk = raw_input("How are you? ")
words = re.split("\\s+", talk)
if 'fine' in words:
    print "Glad to hear it..."
elif 'terrible' in words:
    print "I'm sorry to hear that!"
else:
    print "Huh?"

通过阅读其他答案,我们必须扩展谓词的含义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM