2014-09-20 52 views
0

我想確定輸入是否有效。我有:Python:當raw_input無效時重複函數

servqual = raw_input(">").lower() 
while servqual != "great" or "good" or "lacking" or "poor": 
    print "I didn't understand that. Please try again." 
    servqual = raw_input(">").lower() 

但是,每當我通過循環運行它,它總是假定如此,即使我輸入一個有效的答案。 我查看了不同的答案,但他們都沒有在這種情況下工作。

回答

4
servqual != "great" or "good" or "lacking" or "poor" 

相當於

(servqual != "great") or "good" or "lacking" or "poor" 

而且因爲字符串被認爲True,你總是得到它真正的

正確的方法是

servqual != "great" and servqual != "good" and servqual != "lacking" and servqual != "poor" 

servqual not in ("great", "good", "lacking", "poor") 

你的最終代碼看起來像

servqual = raw_input(">").lower() 
while servqual not in ("great", "good", "lacking", "poor"): 
    print "I didn't understand that. Please try again." 
    servqual = raw_input(">").lower() 

您可以進一步通過下面的步驟來改善它。

while raw_input(">").lower() not in ("great", "good", "lacking", "poor"): 
    print "I didn't understand that. Please try again." 
+0

謝謝,這工作得很好! – sfowler12 2014-09-20 22:00:30

1

您有:

while servqual != "great" or "good" or "lacking" or "poor": 

這意味着相同的:

while (servqual != "great") or "good" or "lacking" or "poor" 

由於"good" or "lacking" or "poor"始終是真實的,整個情況是真實的。

比相反,你可以這樣做:

while servqual not in ("great", "good", "lacking", "poor"): 
    ...