2013-07-15 174 views
1

我想添加一個if語句來檢查無效輸入。如果用戶輸入「是」,並且如果用戶輸入「否」,則結束它的工作。但是出於某種奇怪的原因,不管答案是什麼:是的,不,隨機的字符等等。它總是打印「無效輸入」語句。我試圖僅在答案不是「是」或「否」時纔打印。如果語句總是打印(Python)

while cont == "Yes": 
    word=input("Please enter the word you would like to scan for. ") #Asks for word 
    capitalized= word.capitalize() 
    lowercase= word.lower() 
    accumulator = 0 

    print ("\n") 
    print ("\n")  #making it pretty 
    print ("Searching...") 

    fileScan= open(fileName, 'r') #Opens file 

    for line in fileScan.read().split(): #reads a line of the file and stores 
     line=line.rstrip("\n") 
     if line == capitalized or line == lowercase: 
      accumulator += 1 
    fileScan.close 

    print ("The word", word, "is in the file", accumulator, "times.") 

    cont = input ('Type "Yes" to check for another word or \ 
"No" to quit. ') #deciding next step 
    cont = cont.capitalize() 

    if cont != "No" or cont != "Yes": 
     print ("Invalid input!") 

print ("Thanks for using How Many!") #ending 

回答

2

if cont != "No" or cont != "Yes":

兩個YesNo sastisfy這種情況下

應該cont != "No" and cont != "Yes"

2

續永遠要麼不等於 「否」 或不等於 「是」。你想要and而不是or

,或者替換地

if cont not in ['No', 'Yes']: 

,如果你想,例如,加小寫這將是更具擴展性。

+0

哦,我的天哪。我怎麼沒有注意到這一點。哈哈哈非常感謝你:) –

2

if cont != "No" or cont != "Yes"的意思是「如果答案不是否或不是」。一切都不是不是或者不是,因爲它不能同時存在。

改爲改爲if cont not in ("Yes", "No")

2

您需要and操作而不是or。使用操作,無論輸入值是什麼,您的條件都將評估爲真。條件更改爲:

if cont != "No" and cont != "Yes": 

或簡單地使用:

if cont not in ("No", "Yes"): 
8

這是因爲,無論你輸入,至少一個測試的是正確的:

>>> cont = 'No' 
>>> cont != "No" or cont != "Yes" 
True 
>>> (cont != "No", cont != "Yes") 
(False, True) 
>>> cont = 'Yes' 
>>> cont != "No" or cont != "Yes" 
True 
>>> (cont != "No", cont != "Yes") 
(True, False) 

使用and代替:

>>> cont != 'No' and cont != 'Yes' 
False 
>>> cont = 'Foo' 
>>> cont != 'No' and cont != 'Yes' 
True 

,或者使用一個成員資格測試(in):

>>> cont not in {'Yes', 'No'} # test against a set of possible values 
True 
-1
if cont != "No" or cont != "Yes": 

還有什麼你可能輸入,不會滿足這個?

+2

這不是一個真正有用的答案。儘管要回答你的問題,你可以創建一個類並定義一個'__ne __()'方法。 – pandubear

+0

@pandubear:+1。一個微不足道的小課堂顯然很愚蠢,但是你回答的問題也是如此(可能會有真實的案例這樣做)。 – abarnert