0

I'm trying to add an if statement to check for invalid input. It's working like it should and looping back again if the user enters "Yes" and ending if the user enters "No". But for some odd reason no matter what the answer: yes, no, random character, etc. It always prints the "invalid input" statement. I'm trying to make that only print when the answer isn't "Yes" or "No".

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

6 Answers 6

8

That's because whatever you enter, at least one of the tests is 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)

Use and instead:

>>> cont != 'No' and cont != 'Yes'
False
>>> cont = 'Foo'
>>> cont != 'No' and cont != 'Yes'
True

or use a membership test (in):

>>> cont not in {'Yes', 'No'}  # test against a set of possible values
True
Sign up to request clarification or add additional context in comments.

Comments

2

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

Both Yes and No sastisfy this condition

It should be cont != "No" and cont != "Yes"

Comments

2

Cont will always either not equal "No" or not equal "Yes". You want and instead of or.

Or, alternately,

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

which will be more extensible if you want to, e.g., add lowercase.

Comments

2

if cont != "No" or cont != "Yes" means "if the answer is not No or it is not Yes". Everything is either not No or not Yes, since it can't be both.

Change it instead to if cont not in ("Yes", "No").

Comments

2

You need an and operation instead of or. Using or operation, your condition will evaluate to true no matter what the input value is. Change the condition to:

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

or simply use:

if cont not in ("No", "Yes"):

Comments

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

What could you possibly input that would not satisfy this?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.