I\'ve written the following code in Python 3.x to validate the user\'s input:
while True:
try:
answer = int(input(\"Enter an integer: \"))
except
Assuming you're using python 3.X, everything the user inputs will be a string. Even numbery looking things like "23" or "0". int(thing)
doesn't validate that thing
is of the integer type. It attempts to convert thing
from whatever type it is now, into the integer type, raising a ValueError if it's impossible.
Demonstration:
>>> while True:
... x = input("Enter something: ")
... print("You entered {}".format(x))
... print("That object's type is: {}".format(type(x)))
...
Enter something: hi
You entered hi
That object's type is:
Enter something: hi46
You entered hi46
That object's type is:
Enter something:
You entered
That object's type is:
Enter something: ]%$
You entered ]%$
That object's type is:
Enter something: 23
You entered 23
That object's type is:
Enter something: 42
You entered 42
That object's type is:
Enter something: 0
You entered 0
That object's type is: