python - If 语句始终打印 (Python)

标签 python if-statement

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

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 = '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' 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

关于python - If 语句始终打印 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17661206/

相关文章:

java - 按顺序从文件中读取一组数字

javascript - 如何优化 3 个条件 if else if 语句

python - python中的模型训练和Golang中的模型运行,模型导入过程中的问题

python - 显示或保存 URL 图像列表

c - if/else 不符合预期

MySQL 中的 Php if 语句用于批量更新

python - 如何在python中调整直方图上的字体大小

python - 在 python3 中加入字符串列表的第一个元素

python - imaplib 代理身份验证

java - 在java中比较单词中的单词