Use string isdigit() method to check user input is number or string. Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work.
You Can Type: user_input = input("Enter something: ") if type(user_input) == int: print(user_input, "Is a number") else: print("Not a number") try: val = int(user_input) except ValueError: print("That's not an int!")
Use the isNaN() Function to Check Whether a Given String Is a Number or Not in JavaScript. The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). The function outputs as True for a NaN value and returns False for a valid numeric value.
Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.
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 https://docs.python.org/3/tutorial/errors.html#handling-exceptions
Apparently this will not work for negative values, but it will for positive numbers.
Use isdigit()
if userinput.isdigit():
#do stuff
The method isnumeric()
will do the job (Documentation for python3.x):
>>>a = '123'
>>>a.isnumeric()
True
But remember:
>>>a = '-1'
>>>a.isnumeric()
False
isnumeric()
returns True if all characters in the string are numeric characters, and there is at least one character.
So negative numbers are not accepted.
For Python 3 the following will work.
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
EDITED: You could also use this below code to find out if its a number or also a negative
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
print "given string is number"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With