如何修复Python elif?

时间:2010-11-16 02:33:13

标签: python

好的,我有以下代码执行我不希望它做的事情。如果你运行该程序,它会问你“你好吗?” (显然),但是当你回答适用于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!"

6 个答案:

答案 0 :(得分:8)

问题是or运算符在此处没有执行您想要的操作。你真正说的是if the value of "good" is True or "fine" is in talk。 “good”的值始终为True,因为它是一个非空字符串,这就是为什么该分支总是被执行。

答案 1 :(得分:4)

if "good" in talk or "fine" in talk就是你的意思。你写的内容相当于if "good" or ("fine" in talk)

答案 2 :(得分:2)

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-block总是被执行的原因。

答案 3 :(得分:2)

使用正则表达式。如果输入是“我很好。如果我更好。抱歉,我感觉很糟糕,我很糟糕。” 然后,您将满足所有条件,输出将不是您所期望的。

答案 4 :(得分:0)

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

在你的代码中,Python将获取字符串的值并测试它们的真实性("good"',“bad”'和"sad"' will return True',因为它们不是空的),然后它将检查谈话中是否存在“精细”字样(因为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!"

答案 5 :(得分:0)

这对我有用:

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

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