2010-11-16 77 views
1

好吧我有下面的代码执行一些我不希望它做的事情。如果你运行该程序,它会问你“你好吗?” (很明显),但是当你给出适用于elif语句的问题的答案时,我仍然得到一个if语句响应。为什么是这样?如何解决Python elif?

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

回答

8

问题是,or运营商没有做你想在这里。你真正说的是if the value of "good" is True or "fine" is in talk。 “good”的值总是为True,因为它是一个非空字符串,这就是为什么该分支总是被执行的原因。

+0

+1 - 很好的解释。 – duffymo 2010-11-16 03:01:17

4

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

+0

谢谢你!这有帮助! – 2010-11-16 02:38:41

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块总是得到执行。

2

使用正则表达式。如果输入是“我很好,那么,我会更好,对不起,我感觉很糟糕,我的不好。” 然后你会满足所有的条件,并且输出不会是你所期望的。

+4

HAHAHAHAHAHAHAHA – slezica 2010-11-16 02:40:33

+0

如果谈话中的“善”和谈话中的“糟糕”:打印“下定决心” – nilamo 2010-11-16 04:30:00

+0

如果这是输入,您认为应该发生什么?正则表达式在这里有点矫枉过正。 – nmichaels 2010-11-16 17:13:56

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!" 
+0

这将排除OP代码能够捕获的各种字符串。 – aaronasterling 2010-11-16 02:43:08

+0

@aaronasterling,谨慎解释?它适用于Ubuntu 10.10 Python 2.6.6。当然,它只做严格的匹配。 – 2010-11-16 03:05:56

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

从阅读其他的答案,我们不得不扩大换句话说谓词。