2012-06-21 113 views
-3

我一直有一個問題,我正在處理一個簡單的代碼。它詢問你的名字,以及你的一天是如何的,並且根據你的答案,它應該做與該答案相關的行動。感謝您提前提供所有幫助。如果條件字符串失敗

import time 
print "Hello." 
time.sleep(.5) 
print "What's your name?" 
var = raw_input() 
time.sleep(.3) 
print "Hello", var 
time.sleep(1) 
print "How are you?" 
i = 0 
answer1 = False 
answer2 = False 
answer0 = False 
repeat = True 
while repeat == True: 
     if i == 0: 
       answer = raw_input() 
     if answer == "Good" or "good": 
       answer1 = True 
     if answer == "Bad" or "bad": 
       answer2 = True 
     if answer is not "good" or "Good" or "ok" or "Ok" or "OK" or "Not so good" or "not so good" or "Not so good." or "not so good.": 
       answer0 = True 
     if answer2 == True: 
       print "That sucks." 
       time.sleep(1) 
       print "Well that's end of my code", var 
       time.sleep(1) 
       print "See ya!" 
       break 
     if answer1 == True: 
       print "That's awesome!" 
       time.sleep(1) 
       print "Well that's end of my code", var 
       time.sleep(1) 
       print "See ya!" 
       break 
     if answer0 == True: 
       print "I'm sorry, I didn't understand you." 
       time.sleep(1.5) 
       print "Are you good, ok, or not so good?"   
+5

又是什麼代碼實際上做? –

+3

...我們應該猜測它實際上**做了什麼嗎? –

+0

如果有什麼打印出來是什麼? –

回答

4

這是錯誤的:

if answer == "Bad" or "bad": 

你可能是指:

if answer == "Bad" or answer == "bad": 

if answer in ("Bad", "bad"): 
2

正如評論說,你應該更具體的瞭解是什麼錯了,但下面一行肯定是:

if answer is not "good" or "Good" or "ok" or "Ok" or "OK" or "Not so good" or "not so good" or "Not so good." or "not so good." 

這看起來應該如

if answer not in ('good', 'Good', ...): 

此外,您可能會發現else子句有時有用。

16

這些條件將永遠是真實的,因爲非空字符串字面量蟒蛇是truthy

if answer == "Good" or "good": 
if answer == "Bad" or "bad": 
if answer is not "good" or "Good" or "ok" ...: 
... 
# is the same as 
if (something == something_else) or (True) or (True) ... :` 

所以replate該代碼:

if answer in ("Good", "good"): 
if answer not in ("good", "Good", "ok", ...): 
.... 

或更好,但如果你希望包括「GOOD」和其他案例變體:

if answer.lower() == "good": 
if answer.lower() not in ("good", "ok", ...): 
... 
+1

+1對於「好」的答案,其中包括'lower()' – JoeFish

+0

@JoeFish通過你的「好答案」的定義,我們應該完全重寫他的所有代碼,因爲它是一個完整的混亂,但它將是脫離主題的題。 – KurzedMetal

1

用這些取代你的病情。

if i == 0: 
     answer = raw_input().strip() #use strip(), because command prompt adds a \n after you hit enter 
     if answer == ("Good") or answer ==("good"): 
       answer1 = True 
     if answer == "Bad" or answer =="bad": 
       answer2 = True 
1

如果您打算使用邏輯運算符,請務必記住您也需要具有布爾值作爲操作數。

含義,在你的代碼

if answer == "Good" or "good": 

您正在嘗試比較,answer == "Good",這將產生一個布爾值,"good",這基本上是一個字符串文字。

爲了解決這個問題,你需要重寫你的條件

if answer == "Good" or answer == "good":