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
You can do this without relying on an exception using isdigit():
answer = input("Enter an integer: ")
while not answer.isdigit():
print("That's not a whole number. Try again.")
answer = input("Enter an integer: ")
answer = int(answer)
isdigit() tests to see if the input string is made up entirely of numbers that can be converted with int().
String, everything that you input()
will be a string. And all of them will raise value error except for C-c
if int()
raises it.
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: <class 'str'>
Enter something: hi46
You entered hi46
That object's type is: <class 'str'>
Enter something:
You entered
That object's type is: <class 'str'>
Enter something: ]%$
You entered ]%$
That object's type is: <class 'str'>
Enter something: 23
You entered 23
That object's type is: <class 'str'>
Enter something: 42
You entered 42
That object's type is: <class 'str'>
Enter something: 0
You entered 0
That object's type is: <class 'str'>