2014-10-26 167 views
0

我遇到了問題,其中包括Python中while循環的多個語句。它適用於單個條件,但是當我包含多個條件時,循環不會終止。我在這裏做錯了什麼?python中的while循環的多個條件

name = raw_input("Please enter a word in the sentence (enter . ! or ? to end.)") 

final = list() 

while (name != ".") or (name != "!") or (name != "?"): 
    final.append(name) 
    print "...currently:", " ".join(final) 
    name = raw_input("Please enter a word in the sentence (enter . ! or ? to end.)") 
print " ".join(final) 

回答

4

您需要使用and;你想要的循環繼續,如果所有條件得到滿足,而不僅僅是一個:

while (name != ".") and (name != "!") and (name != "?"): 

你並不需要但是括號。

更好的將在這裏測試成員:

while name not in '.!?': 
+0

是我的錯。感謝您的幫助,雖然...工作很好 – upendra 2014-10-26 21:43:50

1

這種情況:

(name != ".") or (name != "!") or (name != "?") 

總是正確的。假設所有三個子條件都是錯誤的,這隻會是錯誤的,這將要求 name等於".""!""?"同時。

你的意思是:

while (name != ".") and (name != "!") and (name != "?"): 

,或者更簡單地說,

while name not in { '.', '!', '?' }: 
+0

是的,我意識到我愚蠢的錯誤。謝謝你的好解釋.. – upendra 2014-10-26 21:45:45