How do you check if the input is a number in python?

Looks like there's so far only two answers that handle negatives and decimals (the try... except answer and the regex one?). Found a third answer somewhere a while back somewhere (tried searching for it, but no success) that uses explicit direct checking of each character rather than a full regex.

Looks like it is still quite a lot slower than the try/exceptions method, but if you don't want to mess with those, some use cases may be better compared to regex when doing heavy usage, particularly if some numbers are short/non-negative:

>>> from timeit import timeit

On Python 3.10 on Windows shows representative results for me:

Explicitly check each character:

>>> print(timeit('text="1234"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
0.5673831000458449
>>> print(timeit('text="-4089175.25"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.0832774000009522
>>> print(timeit('text="-97271851234.28975232364"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.9836419000057504

A lot slower than the try/except:

>>> def exception_try(string):
...   try:
...     return type(float(string)) == int
...   except:
...     return false

>>> print(timeit('text="1234"; exception_try(text)', "from __main__ import exception_try"))
0.22721579996868968
>>> print(timeit('text="-4089175.25"; exception_try(text)', "from __main__ import exception_try"))
0.2409859000472352
>>> print(timeit('text="-97271851234.28975232364"; exception_try(text)', "from __main__ import exception_try"))
0.45190039998851717

But a fair bit quicker than regex, unless you have an extremely long string?

>>> print(timeit('import re'))
0.08660140004940331

(In case you're using it already)... and then:

>>> print(timeit('text="1234"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.3882658999646083
>>> print(timeit('text="-4089175.25"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4007637000177056
>>> print(timeit('text="-97271851234.28975232364"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4191589000402018

None are close to the simplest isdecimal, but that of course won't catch the negatives...

>>> print(timeit('text="1234"; text.isdecimal()'))
0.04747540003154427

Always good to have options depending on needs?

In this tutorial, we will learn how to check if user input is a string or number in Python.

We have some tricks to check user input.

Type 1:  type(num) to check input type in Python

num = input("Enter Something:")
print(type(num))

Output:

Enter Something: 5

Enter Something: abc

Type2: isnumeric() function to check if a number is integer or not in Python

Thing = input("Enter Something:")
if Thing.isnumeric():
   print("Entered Thing is Integer:", Thing)
else:
   print("Entered Thing is Not an Integer")

Output:

Enter Something: 123

Entered Thing is Integer: 123




Enter Something: abc

Entered Thing is Not an Integer

Type3:

In this type, we define is_Int as True, if the user entered input, it tries to convert into the integer in that there is a non-numeric character then it goes to the ValueError. In the if condition statement is_Int is True.

thing = input("Enter Something:")
is_Int = True
try:
   int(thing)
expect ValueError:
   is_Int = False
if is_Int:
   print("Entered thing is Integer")
else:
   print("Entered thing is not an Integer")

Output:

Enter Something: 123

Entered thing is Integer




Enter Something: abc

Entered thing is not an Integer

Type4: isdigit() function in Python

thing = 123
if thing.isdigit():
   print("It is Integer")
else:
   print("It is Not a Integer")

Output:

It is Integer

isdigit() function for string in Python

Also read: Python program to check whether given number is Hoax Number

Check if user input is a Number in Python #

Use a try/except statement to check if a user input is a number. If the input value is a number, the try block completes running, otherwise a ValueError is raised which can be handled in the except block.

Copied!

# ✅ Check if user input is number (try/except statement) num = input('Enter your favorite number: ') try: num = float(num) print(num) except ValueError: print('The provided value is not a number') # ----------------------------------------- # ✅ Keep prompting the user until they enter a number (while loop) num = 0 while True: try: num = int(input("Enter your favorite integer: ")) except ValueError: print("Please enter a valid integer") continue else: print(f'You entered: {num}') break

The first example uses a try/except statement to check if the input value is a valid number.

Calling the float() or int() classes with a value that is not a valid number raises a ValueError.

Copied!

num = input('Enter your favorite number: ') try: num = float(num) print(num) except ValueError: print('The provided value is not a number')

How do you check if the input is a number in python?

If the user entered a number, the try block completes and the except block doesn't run.

If the provided value is not a valid number, the except block runs.

If you only need to check if the user input is a valid integer, use the int() class for the conversion.

Copied!

num = input('Enter your favorite integer: ') try: num = int(num) print(num) except ValueError: print('The provided value is not an integer')

Alternatively, you can use the str.isdigit() method.

Check if user input is a Number using str.isdigit() #

Use the str.isdigit() method to check if a user input is a number, e.g. if num.isdigit():. The isdigit() method will return True for all positive integer values and False for all non-numbers, floating-point numbers or negative numbers.

Copied!

num = input('Enter your favorite number: ') if num.isdigit(): print('Provided value is a valid number') num = int(num) print(num) else: print('Provided value is not a number, is a negative number or a float')

The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

Copied!

print('567'.isdigit()) # 👉️ True print('3.14'.isdigit()) # 👉️ False print('-5'.isdigit()) # 👉️ False

Note that the str.isdigit() method returns False for floating-point numbers (they contain a period) and for negative numbers (they contain a minus sign).

You should only use this approach to check if a user input is a valid integer.

You can use a while loop if you need to keep prompting the user until they enter a valid number.

Keep asking for user input until a Number is entered #

The example uses a while True loop to keep iterating until the user enters a valid number.

Copied!

num = 0 while True: try: num = int(input("Enter your favorite integer: ")) except ValueError: print("Please enter a valid integer") continue else: print(f'You entered: {num}') break

How do you check if the input is a number in python?

If the code in the try block raises a ValueError, the except block runs, where we use the continue statement to continue to the next iteration.

If the user enters a valid number, the try block completes successfully and then the else block runs where we use the break statement to exit out of the while loop.

The continue statement continues with the next iteration of the loop.

The break statement breaks out of the innermost enclosing for or while loop.

How do you check that input is a Number?

Check if variable is a number in JavaScript.
isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false..
typeof – If variable is a number, it will returns a string named “number”..

How do you identify a Number in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

How do you check if something is not a number in Python?

Python String isnumeric() Method The str. isnumeric() checks whether all the characters of the string are numeric characters or not. It will return True if all characters are numeric and will return False even if one character is non-numeric.