If语句始终打印(Python)
我试图添加一个if语句来检查无效输入。它正常工作,如果用户输入Yes,它会再次循环,如果用户输入No,它就会结束。但是出于某种奇怪的原因,不管答案是什么:Yes,No,random character,等等。它总是打印无效的输入语句。我只是在回答不是“是”或“否”时才打印出来If语句始终打印(Python),python,if-statement,Python,If Statement,我试图添加一个if语句来检查无效输入。它正常工作,如果用户输入Yes,它会再次循环,如果用户输入No,它就会结束。但是出于某种奇怪的原因,不管答案是什么:Yes,No,random character,等等。它总是打印无效的输入语句。我只是在回答不是“是”或“否”时才打印出来 while cont == "Yes": word=input("Please enter the word you would like to scan for. ") #Asks for word ca
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
如果继续!=否或继续!=是的:
是和否都可以满足这个条件
它应该是cont!=不,继续是如果继续否或继续!=是的:
是和否都可以满足这个条件
它应该是cont!=不,继续是继续将始终不等于否或不等于是。你想要和,而不是或 或者,或者
if cont not in ['No', 'Yes']:
如果您想扩展,例如添加小写。Cont将始终不等于No或不等于Yes。你想要和,而不是或 或者,或者
if cont not in ['No', 'Yes']:
如果您想扩展,例如添加小写字母。if cont!=否或继续!=是的意思是如果答案不是“否”或不是“是”。每件事都不是“不”就是“不”,因为不可能两者兼而有之
将其改为if cont not in Yes,No.if cont!=否或继续!=是的意思是如果答案不是“否”或不是“是”。每件事都不是“不”就是“不”,因为不可能两者兼而有之
将其改为if cont not in Yes,No.您需要and操作而不是or。使用或操作,无论输入值是什么,您的条件都将计算为true。将条件更改为:
if cont != "No" and cont != "Yes":
或者简单地使用:
if cont not in ("No", "Yes"):
您需要and操作而不是or。使用或操作,无论输入值是什么,您的条件都将计算为true。将条件更改为:
if cont != "No" and cont != "Yes":
或者简单地使用:
if cont not in ("No", "Yes"):
这是因为无论您输入什么,至少有一个测试是正确的:
>>> 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)
使用,而不是:
或在以下情况下使用成员资格测试:
这是因为无论您输入什么,至少有一个测试是正确的:
>>> 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)
使用,而不是:
或在以下情况下使用成员资格测试:
您可能会输入哪些不满足此要求的内容
您可能会输入哪些不满足此要求的内容?哦,天哪。我怎么没注意到。哈哈哈,非常感谢你:哦,我的天啊。我怎么没注意到。哈哈哈,非常感谢你:这不是一个真正有用的答案。虽然要回答您的问题,您可以创建一个类并定义一个_____________________方法。@pandubear:+1。一个微不足道的类,但它不是任何事情显然都是愚蠢的,但你回答的问题也是如此,现实生活中可能会有这样的案例。这并不是一个真正有用的答案。虽然要回答您的问题,您可以创建一个类并定义一个_____________________方法。@pandubear:+1。一个微不足道的类,但它不是任何事情显然都是愚蠢的,但你回答的问题也是如此,现实生活中可能会有这样的案例。