我正在尝试添加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
答案 0 :(得分: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 :(得分:2)
if cont != "No" or cont != "Yes":
Yes
和No
都满足这个条件
应为cont != "No" and cont != "Yes"
答案 2 :(得分:2)
Cont将始终不等于“否”或不等于“是”。您需要and
而不是or
。
或者,或者,
if cont not in ['No', 'Yes']:
如果你想要更加可扩展,例如,添加小写。
答案 3 :(得分:2)
if cont != "No" or cont != "Yes"
表示“如果答案不是否,则表示不是”。一切都不是否是,是的,因为它不能同时存在。
将其改为if cont not in ("Yes", "No")
。
答案 4 :(得分:2)
您需要and
操作而不是or
。使用或操作,无论输入值是什么,您的条件都将评估为真。将条件更改为:
if cont != "No" and cont != "Yes":
或只是使用:
if cont not in ("No", "Yes"):
答案 5 :(得分:-1)
if cont != "No" or cont != "Yes":
你可能输入什么不能满足这个要求?