user4512750
user4512750

Reputation:

User input program not working," != "?

Just messing around with Python 3 functions and user inputs, but really scratching my head here as to why != won't work? If the user enters YES or yes it still produces the message "Invalid answer. YES or NO only!"?

Thanks

def program():
    valid_answers = ("YES", "yes", "NO", "no")
    variable_input = input("Are bananas yellow? Answer YES or NO: ")

    if variable_input != valid_answers:
        print("Invalid answer. YES or NO only!")
        program()

    elif variable_input == "YES":
        print("Correct! They are!")
        program()
    elif variable_input == "yes":
        print("Correct! They are!")
        program()
    elif variable_input == "NO":
        print("Try again. They are definitely yellow.")
        program()
    elif variable_input == "no":
        print("Try again. They are definitely yellow.")
        program()
program()

Upvotes: 0

Views: 98

Answers (3)

Dilyan Dokov
Dilyan Dokov

Reputation: 33

Correction:

if variable_input != valid_answers: should be if variable_input not in valid_answers:

And you can reduce the if statement like this:

Final program:

def program():
    valid_answers = ("YES", "yes", "NO", "no")
    variable_input = input("Are bananas yellow? Answer YES or NO: ")

    if variable_input not in valid_answers:
        print("Invalid answer. YES or NO only!")
        program()
    elif variable_input in ["YES", "yes"]: 
        print("Correct! They are!")
        program()
    elif variable_input in ["NO", "no"]:
        print("Try again. They are definitely yellow.")
        program()

program()

Upvotes: 1

Zizouz212
Zizouz212

Reputation: 4998

First off, I would make valid_answers a list. != means not equal or equivalent to. Instead of !=, you not in.You should write the code like this:

def program():
    valid_answers = ["YES", "yes", "NO", "no"] # Note the change from tuple to list
    variable_input = input("Are bananas yellow? Answer YES or NO: ")

    if variable_input not in valid_answers: # Note the != to not in
        # do something

    # rest of your code

Responding to the comment...

For the multiple options in input, you could use a tuple and "scan" it to see if variable_input exists in the tuple, and then follow an action like so:

elif variable_input == ("yes", "YES"):
    # do something

Now, if I remember correctly, in Python 3 you can also use the or operator instead of a tuple. :)

Upvotes: 2

Dair
Dair

Reputation: 16240

You're checking if the variable_input literally does not equal the tuple. You want to check if variable_input is not in the tuple.

if variable_input != valid_answers:

Should be:

if variable_input not in valid_answers:

Upvotes: 1

Related Questions