1

我正在尝试添加一个 if 语句来检查无效输入。如果用户输入“是”,它会正常工作并再次循环返回,如果用户输入“否”则结束。但是出于某种奇怪的原因,无论答案是什么:是,否,随机字符等。它总是打印“无效输入”语句。我试图仅在答案不是“是”或“否”时才打印。

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
4

6 回答 6

8

那是因为无论你输入什么,至少有一个测试是 True:

>>> 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
于 2013-07-15T18:28:45.140 回答
2

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

都满足这个Yes条件No

它应该是cont != "No" and cont != "Yes"

于 2013-07-15T18:27:51.367 回答
2

Cont 将始终不等于“否”或不等于“是”。你想要and而不是or.

或者,或者,

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

如果您想添加小写,这将更具可扩展性。

于 2013-07-15T18:28:12.343 回答
2

if cont != "No" or cont != "Yes"意思是“如果答案不是否或不是”。一切都不是“否”或“不是”,因为不可能两者兼而有之。

改为if cont not in ("Yes", "No").

于 2013-07-15T18:28:26.303 回答
2

您需要一个and操作而不是or. 使用or操作,无论输入值是什么,您的条件都将评估为真。将条件更改为:

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

或简单地使用:

if cont not in ("No", "Yes"):
于 2013-07-15T18:28:28.477 回答
-1
if cont != "No" or cont != "Yes":

你可以输入什么不能满足这个要求?

于 2013-07-15T18:30:21.057 回答