isFloat: Without Exception-Handling

Steve Holden sholden at holdenweb.com
Wed Sep 18 12:47:40 EDT 2002


"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

Also note that, were your test the right one, it would be much more concise
to write the function as

    def isFloat(s):
        return type(s) == type(1.0)

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------






More information about the Python-list mailing list