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.
natural: [0, 1, 2 ... ∞]
Python 2
Python 3
integer: [-∞, .., -2, -1, 0, 1, 2, ∞]
float: [-∞, .., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1, ..., ∞]
If you wanted to evaluate floats, and you wanted to accept
NaN
s as input but not other strings like'abc'
, you could do the following:EDITED: You could also use this below code to find out if its a number or also a negative
you could also change your format to your specific requirement. I am seeing this post a little too late.but hope this helps other persons who are looking for answers :) . let me know if anythings wrong in the given code.
Here is a simple function that checks input for INT and RANGE. Here, returns 'True' if input is integer between 1-100, 'False' otherwise
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()
I would recommend this, @karthik27, for negative numbers
Then do whatever you want with that regular expression, match(), findall() etc