2013-07-15 78 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