In this tutorial, we will look at how to check if a user input in Python is a number or not with the help of some examples.
How to check if the user input is a number?
In Python, we receive the value from the standard input as strings. Now, to check if the input is a number or not, check if the input string is numeric or not.
There are multiple ways to check if a string is numeric (contains only numeric data) or not in Python. For example –
- Try to convert the string into a
float
(orint
) type inside atry
…except
block. If the code raises an error, we can say that the input string is not numeric. - Use the string built-in
isdigit()
function. - Use the string built-in
isnumeric()
function.
Examples
Let’s now look at some examples so using the above syntax. First, we will take some values as input and then use them throughout this tutorial.
# take input from the user s1 = input("Enter the first value\n") s2 = input("Enter the second value\n") s3 = input("Enter the third value\n") s4 = input("Enter the fourth value\n") # display the entered values for s in [s1, s2, s3, s4]: print(f"Entered value: {s} has type: {type(s)}")
Output:
Enter the first value 21 Enter the second value 3.14 Enter the third value cat Enter the fourth value Entered value: 21 has type: <class 'str'> Entered value: 3.14 has type: <class 'str'> Entered value: cat has type: <class 'str'> Entered value: has type: <class 'str'>
Here, we take four values as input from the user – s1
, s2
, s3
, and s4
. All the values from the standard input are of string type. You can see that the string s1
is a numeric string, s2
is also a numeric string (with a decimal point), s3
contains alphabetical characters, and s4
is an empty string.
Method 1 – Using type conversion inside try
… except
You can also use error handling to check if the string input is a number or not.
The idea is to try to convert the string input to a numeric type (like int
or float
) inside a try
block. Now, if this conversion raises a ValueError
, we can say that the input is not a number.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
Let’s apply this method to the numeric string s1
created above.
# check if s1 is numeric or not try: # convert string to float float(s1) print("Input is a number") except ValueError: print("Type conversion failed, input is not a number")
Output:
Input is a number
Now, let’s apply this method to all the strings created above.
# check if input string is a number for s in [s1, s2, s3, s4]: print("For ", s) try: # convert string to int float(s) print("Input is a number") except ValueError: print("Type conversion failed, input is not a number")
Output:
For 21 Input is a number For 3.14 Input is a number For cat Type conversion failed, input is not a number For Type conversion failed, input is not a number
The error-handling method correctly identified the numeric strings (s1
and s2
) in the above example.
Method 2 – Using the string isdigit()
function
The string isdigit()
function takes a string and returns True
if all the characters in the string are numeric characters and there is at least one character in the string. It returns False
otherwise.
Let’s now use this method on the four input strings we created above.
# check if input string is a number print(s1.isdigit()) print(s2.isdigit()) print(s3.isdigit()) print(s4.isdigit())
Output:
True False False False
We get True
for s1
and False
for s2
, s3
and s4
.
Notice that, here, we get False
for s2
which is “3.14”. The reason we get False
is because of the “.” character present in the number.
So, the isdigit()
function doesn’t directly work for numbers with decimal values but there’s a workaround. You can first replace any '.'
characters with an empty string and then proceed to use the isdigit()
function.
# check if input string with decimal is a number print(s2.replace(".", "").isdigit())
Output:
True
Now we get True
for s2
(it correctly identifies it as a numeric value).
Method 3 – Using the string isnumeric()
function
The string isnumeric()
function, similar to the isdigit()
function returns True
if all the characters in a string are numeric characters and there’s at least one character in the string. Otherwise, it returns False
.
Let’s now apply this function to the strings created above.
# check if input string is a number print(s1.isnumeric()) print(s2.isnumeric()) print(s3.isnumeric()) print(s4.isnumeric())
Output:
True False False False
We get True
for s1
and False
for s2
, s3
and s4
. Same as the above example.
Notice that, here, similar to the above example, we get False
for s2
which is “3.14”. The reason we get False
is because of the “.” character present in the number.
So, the isnumeric()
function doesn’t directly work for numbers with decimal values but there’s a workaround. You can first replace any '.'
characters with an empty string and then proceed to use the isnumeric()
function.
# check if input string with decimal is a number print(s2.replace(".", "").isnumeric())
Output:
True
Now, we get True
for s2
(it correctly identifies it as a numeric value).
Summary
In this tutorial, we looked at multiple ways to check if the user input is a number or not. The following are the methods covered –
- Trying to convert the input to a numeric type (for example,
float
) inside atry
block and catch anyValueError
s that may occur. - Use the string
isdigit()
function. Remember to remove any'.'
characters in the string to identify numeric strings with decimal values. - Use the string
isnumeric()
function. Remember to remove any'.'
characters in the string to identify numeric strings with decimal values.
You might also be interested in –
- Python – Check if String Contains Only Numbers
- Extract Numbers From String in Python
- Python – Convert Integer to String
- Python – Check If String starts with a Number
- Python – Check If String Ends with a Number
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.