isFloat: Without Exception-Handling
Byron Morgan
lazypointer at yahoo.com
Thu Jun 12 02:22:19 EDT 2003
This works:
import operator
def isFloat(f):
if not operator.isNumberType(f):
return 0
if f % 1:
return 1
else:
return 0
>>> isFloat(3.1)
1
>>> isFloat('a')
0
>>> isFloat(12345)
0
Byron Morgan
> > "Rajarshi Guha" <rajarshi at presidency.com> wrote in message
> > news:pan.2002.09.18.11.40.50.766802.29524 at presidency.com...
> >> On Wed, 18 Sep 2002 11:41:47 -0400, Thomas Guettler wrote:
> >>
> >> > Hi!
> >> >
> >> > Is there a way to write the following method without using
> >> > exceptions?
> >> >
> >> > def isFloat(string):
> >> > is_float=1
> >> > try:
> >> > float(string)
> >> > except:
> >> > is_float=0
> >> > return is_float
> >> >
> >> > print isFloat("asdf") # --> 0
> >> > print isFloat("0.1") # --> 1
> >>
> >>
> >> def isFloat(string):
> >> if type(string) == type(1.0):
> >> return 1
> >> else
> >> return 0
> >>
> >> This should do what you want without exceptions
> >
> > I doubt that VERY much. Please test your code before submitting, or
> > ensure you note it wasn't tested ...
> >
> >>>> def isFloat(s):
> > ... if type(s) == type(1.0):
> > ... return 1
> > ... else:
> > ... return 0
> > ...
> >>>> isFloat("banana")
> > 0
> >>>> isFloat("1.2")
> > 0
>
> If its called as isFloat(1.2) it works.
> (My idea was that it would called with a variable and not a literl)
>
More information about the Python-list
mailing list