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.
You can use the isdigit() method for strings. In this case, as you said the input is always a string:
Here is the simplest solution:
Works fine for check if an input is a positive Integer AND in a specific range
Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.
Result:
I've been using a different approach I thought I'd share. Start with creating a valid range:
Now ask for a number and if not in list continue asking:
Lastly convert to int (which will work because list only contains integers as strings:
If you specifically need an int or float, you could try "is not int" or "is not float":
If you only need to work with ints, then the most elegant solution I've seen is the ".isdigit()" method: