The input()
built-in function returns a value of type str
.
As is specified in the (doc)string right after the declaration of function get_input()
:
You will need a type conversion.
So, you must wrap it in an int()
to convert it to an integer int
.
n = int(input("Enter the number 1,2 or 3? "))
Then you can use comparison operators to evaluate if it is in
the qualified range of accepted values :
# Your comparisons are mixed.
# You can use the in operator which is intuitive and expressive
while n not in [1, 2, 3]:
print("Invalid Input, give the number between 1 to 3")
# remember to wrap it in an int() call again
n = int(input ("Enter the number 1,2 or 3? "))
return (n)
If you supply numbers this works perfectly:
Enter the number 1,2 and 3? 10
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? -1
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? 15
Invalid Input, give the number between 1 to 3
Enter the number 1,2 and 3? 104
Invalid Input, give the number between 1 to 3
But if you supply a single character or a string (type str
), you'll get an error:
Enter the number 1,2 and 3? a
ValueError: invalid literal for int() with base 10: 'a'
This is beyond the scope of the question but you might want to look into it.
Anyway, your while condition is setting me off..
It seems that you might be using Python 2
with the print_function
imported through __future__
. (or else the comparison between different types would raise a TypeError
in the while
statement).
Check your version of python python -V
[in the command line] and:
If using python 2 instead of input()
use raw_input()
:
n = int(raw_input("Enter the number 1, 2, 3: ")
If I am wrong and you are indeed using Python 3.x
, use int(input())
as explained.