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 : ")
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
user1995933
  • 209
  • 1
  • 3
  • 7

3 Answers3

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")
ergonaut
  • 6,929
  • 1
  • 17
  • 47
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") :
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
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 : "))
Om Nigam
  • 122
  • 1
  • 12