Python-Check if user input is a number


Python-Check if user input is a number

In this article, we will discuss if the user input data is a numeric value or not in python.

The input function in python is used to take user input. And every data that the user inputs is converted into a string and returned. And a number in python can be an integer or a floating value.

user_input = input('Enter a number: ')
print(type(user_input))

Output:

Enter a number: 1234
<class 'str'>

As you can see, the input is a number but when we check its data type, it is shown as a string.

Now, how do we know if the input is actually a numerical value?

In Python, we can check if an input is a number or a string:

  1. Using in-built methods likes isdigit() or isnumeric(), which can determine if the user input is a number or not. Or
  2. Using int() or float() functions to convert the input into a numerical value.

Let's understand it with the help of some examples:

Check if the input is a number using int() or float() in Python

The int() or float() method is used to convert any input string to a number. We can use this function to check if the user input is a valid number.

If the user input is successfully converted to a number using int() or float(), it will be considered as a numeric value, if not it's a string.

Example:

user_input = input('Enter a number: ')

data = int(user_input)

print('The number is:', data)

Output:

Enter a number: 123
The number is: 123

Here, as the input value is a valid number, it gets converted successfully to a number.

We can use float() instead of the int(), as it can handle decimal numbers too.

Now, let's see what will happen if the user input is a letter or a character.

Enter a number: abc
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    data = int(user_input)
ValueError: invalid literal for int() with base 10: 'abc'

As the input was a string, it didn't get converted to a number and so we get an error in the terminal.

We can make a slight modification to our program to handle such errors properly using try/except statement.

user_input = input('Enter a number: ')

try:
    data = float(user_input)
    print('The number is:', data)
except ValueError:
    print("The input is not a valid number")

Output:

Enter a number: abc
The input is not a valid number

If the input is a valid number, the try block will run, and if not the except block will run and give us the error message.

Prevent user from entering non-numerical values in input

We can use while loop to keep prompting the user with the message "Enter a number" until they enter a valid number.

while True:
    user_input = input('Enter a number: ')
    try:
        data = float(user_input)
        print('The number is:', data)
        break
    except ValueError:
        print("The input is not a valid number")

Output:

check user input and prevent them from using non-numerical value

Here, the while loop keeps on iterating until the user enters a valid number. Once the valid number is entered, the break statement is executed to exit the program.

Using isdigit() method to check if the input is a number

The isdigit() methods returns True, if all the characters in the string are digits. If not it will return False.

Example:

print(' '.isdigit()) #False
print('123'.isdigit()) #True
print('1.23'.isdigit()) #False
print('abc'.isdigit()) #False

Note: isdigit() method returns False, if the user input is a decimal number or whitespaces.

Now, we can use this isdigit() method with if else statement to check for a valid numerical user input.

Example:

user_input = input('Enter a number: ')

if user_input.isdigit():
    print('The number is :',user_input)
else:
    print('Please enter a valid number')

Output:

Enter a number: 123
The number is : 123

Using isnumeric() method to check if the input is a numerical value

The isnumeric() method just like the isdigit() method, returns True for a numerical value and False for non-numerical values.

However, the key difference between both the method is that, isnumeric() method returns True for unicode fractions and Roman numerals, whereas isdigit() will return False for the same.

Example:

print('ⅶ'.isdigit()) #False
print('ⅶ'.isnumeric()) #True

We can write the same program as above to determine if the user input is a numeric value.

user_input = input('Enter a number: ')

if user_input.isnumeric():
    print('The number is :',user_input)
else:
    print('Please enter a valid number')

Output:

Enter a number: 123
The number is : 123

Related Topics:

Check if user input is empty in python

How to take input as int (integer) in python?