How to validate value is numeric using Python

Introduction

We will see how to validate a value is numeric or not in Python programming language. Situation may occur when you need to validate the input field’s value is numeric or not. The input field on the form may accept anything unless otherwise you have a client side validation.

The user may input anything into the input field and it is developer’s responsibility to validate the input value. The input field may allow float or double value or integer but no special character or letter.

In this example we are going to validate the input field and will return true or false based on the input value.

If the value is integer then we will return true, if the value is double or float then we will return true, if there is any alphanumeric character or letter or two periods or dots (.) then we will return false.

Prerequisites

Python 3.8.0

Numeric Validation

We will create a function that will validate the input value. This function can be used in any Python based application, whether standalone or web application.

def is_numeric(val):
	if str(val).isdigit():
		return True
	elif str(val).replace('.','',1).isdigit():
		return True
	else:
		return False

As we cannot apply isdigit() method on numeric value so we need to first convert it into string.

Testing the Program

Now calling the above function with different values as shown will give you the expected output.

print(is_numeric(1234))
print(is_numeric(1234.23))
print(is_numeric(1234.234))
print(is_numeric('1234.23.4'))
print(is_numeric('1234s'))

Output

True
True
True
False
False

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *