[Tutor] Recognizing real numbers
Steven D'Aprano
steve at pearwood.info
Wed Feb 22 08:47:06 CET 2012
On Tue, Feb 21, 2012 at 07:00:40PM -0800, Michael Lewis wrote:
> It seems that the .isdigit() function that I use doesn't recognize the .5
> as a number and therefore doesn't multiply it. How can I get my code to
> recognize numbers such as .5, 1.75 as numbers?
As the saying goes, it is often Easier to Ask for Forgiveness than
Permission ("EAFP").
In Python terms, that means when you want to do something, just do it,
and then catch the exception if it fails. Wrap this in a function, and
it allows you to use a nifty Look Before You Leap ("LBYL") style of
programming:
def isfloat(obj):
"""Return True if obj is a number or string-like floating point
number.
"""
try:
float(obj)
except (TypeError, ValueError):
return False
else: # no errors
return True
And some examples of it in use:
>>> isfloat("123.456")
True
>>> isfloat("123.45...6")
False
>>> isfloat(".1")
True
>>> isfloat("1.1e6") # 1.1 million
True
>>> isfloat("1.1g6")
False
>>> isfloat("+.1")
True
>>> isfloat(".")
False
--
Steven
More information about the Tutor
mailing list