This question already has an answer here:
How do I check if a user's string input is a number (e.g. -1
, 0
, 1
, etc.)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
The above won't work since input
always returns a string.
For Python 3 the following will work.
Simply try converting it to an int and then bailing out if it doesn't work.
This makes a loop to check whether input is an integer or not, result would look like below:
try this! it worked for me even if I input negative numbers.
I also ran into problems this morning with users being able to enter non-integer responses to my specific request for an integer.
This was the solution that ended up working well for me to force an answer I wanted:
I would get exceptions before even reaching the try: statement when I used
and the user entered "J" or any other non-integer character. It worked out best to take it as raw input, check to see if that raw input could be converted to an integer, and then convert it afterward.