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.
This works with any number, including a fraction:
This solution will accept only integers and nothing but integers.
I think that what you'd be looking for here is the method
isnumeric()
(Documentation for python3.x):Hope this helps
the most elegant solutions would be the already proposed,
Unfortunatelly it doesn't work both for negative integers and for general float values of a. If your point is to check if 'a' is a generic number beyond integers i'd suggest the following one, which works for every kind of float and integer :). Here is the test:
I hope you find it useful :)
I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):
This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)
Based on inspiration from answer. I defined a function as below. Looks like its working fine. Please let me know if you find any issue