0

I want the user to input either 1, 2 or 3. But when I test it and enter 1,2 or 3 it still runs even though the condition is False. I keep changing the condition from and's and or's but I can't seem to solve it. Any help would be greatly appreciated.

def get_input():
    user_input = input("Enter a number 1,2 or 3:  ")

    while  (user_input != 1) and (user_input != 2) and (user_input != 3) :
        print('Invaild input!')
        user_input = input("Enter a number 1,2 or 3 : ")
6
  • Your assumption is wrong. The program is running as it has been told to do. Thus the expression is not false. Commented Oct 4, 2015 at 1:59
  • 1
    You have values of different types -- "1" != 1 # True Commented Oct 4, 2015 at 2:01
  • Thanks Jonathan, but how to deal with the user entering a string or a number that isnt 1 2 or 3 Commented Oct 4, 2015 at 2:02
  • 1
    You need to either test against strings or convert the input to an int. Commented Oct 4, 2015 at 2:04
  • 2
    There is probably a dupe of this somewhere, but that proposed dupe definitely isnt it. Commented Oct 4, 2015 at 2:05

3 Answers 3

1

You are reading strings, you should either convert it, or use strings. So the condition should be

(user_input != "1") and (user_input != "2") and (user_input != "3")
Sign up to request clarification or add additional context in comments.

Comments

1

Because the value returned from input() is a string (enclosed by quote marks), not an integer.

ie.

"1" is not the same thing as 1

To fix it change this line.

while  (user_input != "1") and (user_input != "2") and (user_input != "3") :

Comments

0

You can try to change the input data type to integer from string or rather use "2" instead of 2 in your code

For Using It Without Changing The Data Type:

def get_input():
user_input = input("Enter a number 1,2 or 3:  ")

while  (user_input != "1") and (user_input != "2") and (user_input != "3") :
    print('Invaild input!')
    user_input = input("Enter a number 1,2 or 3 : ")

For changing data type to int:

def get_input():
user_input = int(input("Enter a number 1,2 or 3:  "))

while  (user_input != 1) and (user_input != 2) and (user_input != 3) :
    print('Invaild input!')
    user_input = int(input("Enter a number 1,2 or 3 : "))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.