Question
Asked By – Trufa
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.
Now we will see solution for issue: How to check if string input is a number?
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!")
See Handling Exceptions in the official tutorial.
This question is answered By – Daniel DiPaolo
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0