How to check if string input is a number?


Question

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.

1
123
3/3/2017 7:42:51 PM

Accepted Answer

Simply try converting it to an int and then bailing out if it doesn't work.

try:
   val = int(userInput)
except ValueError:
   print("That's not an int!")
233
3/24/2011 7:53:47 PM

Apparently this will not work for negative values, but it will for positive. Sorry about that, just learned about this a few hours ago myself as I have just recently gotten into Python.

Use isdigit()

if userinput.isdigit():
    #do stuff

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon