2010-11-16 75 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?" 

從閱讀其他的答案,我們不得不擴大換句話說謂詞。