Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if a value is numeric

How can we write a test that checks if a value is numeric, and throw an exception is the value is not numeric? Do we need regular expressions in this case?

Thanks.

like image 722
Simplicity Avatar asked Mar 20 '26 19:03

Simplicity


1 Answers

You can use the numbers module.

>>> import numbers
>>> isinstance(1, numbers.Number)
True
>>> isinstance('a', numbers.Number)
False

It should be noted that complex numbers are considered part of numbers.Number as well, if you only want real numbers you can do:

>>> import numbers
>>> isinstance(1, numbers.Real)
True
>>> isinstance(1j, numbers.Real)
False

As far as throwing an exception if a value is not numeric I would just do:

assert isinstance(my_value, numbers.Real)

Which will throw AssertionError if my_value is not a real number.

like image 178
CrazyCasta Avatar answered Mar 23 '26 09:03

CrazyCasta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!