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
  • 45,449
  • 17
  • 80
  • 115
user1995933
  • 199
  • 1
  • 2
  • 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,701
  • 1
  • 15
  • 45
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
  • 9,419
  • 24
  • 94
  • 167
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
  • 187
  • 9