Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #73392 > unrolled thread

how to check if a value is a floating point or not

Started bynicholascannon1@gmail.com
First post2014-06-18 22:53 -0700
Last post2014-06-20 09:44 -0600
Articles 14 — 9 participants

Back to article view | Back to comp.lang.python


Contents

  how to check if a value is a floating point or not nicholascannon1@gmail.com - 2014-06-18 22:53 -0700
    Re: how to check if a value is a floating point or not Gary Herron <gary.herron@islandtraining.com> - 2014-06-18 23:22 -0700
    Re: how to check if a value is a floating point or not Nicholas Cannon <nicholascannon1@gmail.com> - 2014-06-18 23:48 -0700
      Re: how to check if a value is a floating point or not Ben Finney <ben@benfinney.id.au> - 2014-06-19 17:19 +1000
      Re: how to check if a value is a floating point or not Ian Kelly <ian.g.kelly@gmail.com> - 2014-06-19 01:23 -0600
      Re: how to check if a value is a floating point or not Ian Kelly <ian.g.kelly@gmail.com> - 2014-06-19 01:37 -0600
    Re: how to check if a value is a floating point or not Sturla Molden <sturla.molden@gmail.com> - 2014-06-19 13:46 +0000
    Re: how to check if a value is a floating point or not Nicholas Cannon <nicholascannon1@gmail.com> - 2014-06-19 23:14 -0700
      Re: how to check if a value is a floating point or not Ian Kelly <ian.g.kelly@gmail.com> - 2014-06-20 00:22 -0600
      Re: how to check if a value is a floating point or not Sturla Molden <sturla.molden@gmail.com> - 2014-06-20 13:16 +0000
      Re: how to check if a value is a floating point or not Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-06-20 14:40 +0100
        Re: how to check if a value is a floating point or not Grant Edwards <invalid@invalid.invalid> - 2014-06-20 14:28 +0000
          Re: how to check if a value is a floating point or not alister <alister.nospam.ware@ntlworld.com> - 2014-06-20 15:15 +0000
          Re: how to check if a value is a floating point or not Ian Kelly <ian.g.kelly@gmail.com> - 2014-06-20 09:44 -0600

#73392 — how to check if a value is a floating point or not

Fromnicholascannon1@gmail.com
Date2014-06-18 22:53 -0700
Subjecthow to check if a value is a floating point or not
Message-ID<d5ca21d7-23e6-4240-83d8-262d0f877f7e@googlegroups.com>
I am making a calculator and i need it to support floating point values but i am using the function isnumeric to check if the user has entered an int value. I need the same for floating point types so i could implement an or in the if statement that checks the values the user has entered and allow it to check and use floating points. If you need the source code i am happy to give it to you. Thank you for your help

[toc] | [next] | [standalone]


#73393

FromGary Herron <gary.herron@islandtraining.com>
Date2014-06-18 23:22 -0700
Message-ID<mailman.11130.1403159518.18130.python-list@python.org>
In reply to#73392
On 06/18/2014 10:53 PM, nicholascannon1@gmail.com wrote:
> I am making a calculator and i need it to support floating point values but i am using the function isnumeric to check if the user has entered an int value. I need the same for floating point types so i could implement an or in the if statement that checks the values the user has entered and allow it to check and use floating points. If you need the source code i am happy to give it to you. Thank you for your help

Your mention of *isnumeric* indicates to me that you are using Python3 
(correct?) and are wishing to test if a *string* contains characters 
that represent an int or a float (correct?).

The easiest way to test such is to just try to convert it to an int or 
float, and catch failures as an indication that it is not valid. 
Something like:

try:
   value = float(s)
except ValueError:
    ... handle invalid string ...


Gary Herron

[toc] | [prev] | [next] | [standalone]


#73394

FromNicholas Cannon <nicholascannon1@gmail.com>
Date2014-06-18 23:48 -0700
Message-ID<52ba65d1-a5dc-47b5-bccd-e05b24ae3e1f@googlegroups.com>
In reply to#73392
On Thursday, June 19, 2014 1:53:31 PM UTC+8, Nicholas Cannon wrote:
> I am making a calculator and i need it to support floating point values but i am using the function isnumeric to check if the user has entered an int value. I need the same for floating point types so i could implement an or in the if statement that checks the values the user has entered and allow it to check and use floating points. If you need the source code i am happy to give it to you. Thank you for your help

I am using python 2.7.7 and i have come up with away but there is still possible errors for this. What i did was i this

#checks if the user input is an integer value
def checkint(a):
	if a.isnumeric():
		return True
	else:
		if a.isalpha():
			return False
		else:
			return True

The parameter a is the users input by the raw_input function. I first test if it is normal int with the isnumeric function. Unfortunately this function picks up the decimal as false. This means if the user inputs a float it has to be false. I then test if this input has any alphabetical characters if it does not the user could have only entered  something like 12.5 oppose to abc.d. This method works fine and it i have  tested it and it works fine. if incase this input did have a letter it would be picked up by the isalpha function. There is one annoying error doing it this way and that is if you enter 12.ab or ab.12 it will say that it is okay. Still working on this so this should get sorted out soon.

[toc] | [prev] | [next] | [standalone]


#73398

FromBen Finney <ben@benfinney.id.au>
Date2014-06-19 17:19 +1000
Message-ID<mailman.11132.1403162399.18130.python-list@python.org>
In reply to#73394
Nicholas Cannon <nicholascannon1@gmail.com> writes:

> #checks if the user input is an integer value
> def checkint(a):
> 	if a.isnumeric():
> 		return True
> 	else:
> 		if a.isalpha():
> 			return False
> 		else:
> 			return True

What code will be using this function? Why would that not be better
replaced with a ‘try … except’ construction?

That is, don't do this (Look Before You Leap)::

    foo = get_a_string()
    if checkint(foo):
        bar = int(foo)
    else:
        bar = None

Instead, do this (Easier to Ask Forgiveness than Permission)::

    foo = get_a_string()
    try:
        bar = int(foo)
    except ValueError:
        bar = None

If you need to create an integer based on a string, just do it, and
handle the exception (if any) at an appropriate level.

> There is one annoying error doing it this way and that is if you enter
> 12.ab or ab.12 it will say that it is okay. Still working on this so
> this should get sorted out soon.

You are re-inventing a wheel (the ‘int’ callable) which already does all
of that properly. Make use of it, and your frustration will be reduced.

-- 
 \     “It is far better to grasp the universe as it really is than to |
  `\    persist in delusion, however satisfying and reassuring.” —Carl |
_o__)                                                            Sagan |
Ben Finney

[toc] | [prev] | [next] | [standalone]


#73399

FromIan Kelly <ian.g.kelly@gmail.com>
Date2014-06-19 01:23 -0600
Message-ID<mailman.11133.1403162953.18130.python-list@python.org>
In reply to#73394
On Thu, Jun 19, 2014 at 12:48 AM, Nicholas Cannon
<nicholascannon1@gmail.com> wrote:
> On Thursday, June 19, 2014 1:53:31 PM UTC+8, Nicholas Cannon wrote:
>> I am making a calculator and i need it to support floating point values but i am using the function isnumeric to check if the user has entered an int value. I need the same for floating point types so i could implement an or in the if statement that checks the values the user has entered and allow it to check and use floating points. If you need the source code i am happy to give it to you. Thank you for your help
>
> I am using python 2.7.7 and i have come up with away but there is still possible errors for this. What i did was i this
>
> #checks if the user input is an integer value
> def checkint(a):
>         if a.isnumeric():
>                 return True
>         else:
>                 if a.isalpha():
>                         return False
>                 else:
>                         return True
>
> The parameter a is the users input by the raw_input function. I first test if it is normal int with the isnumeric function. Unfortunately this function picks up the decimal as false. This means if the user inputs a float it has to be false. I then test if this input has any alphabetical characters if it does not the user could have only entered  something like 12.5 oppose to abc.d.

unicode.isalpha does not test if the input has *any* alphabetic
characters.  It tests if the input is *only* alphabetic characters.
u'12.5'.isalpha() does return False.  u'abc.d'.isalpha() *also*
returns False, because the decimal point is not alphabetic.

I second Gary Herron's suggestion to just try converting the value and
catch the exception if it fails.  Python already knows how to do this
for you; there's no need to reinvent the wheel.

[toc] | [prev] | [next] | [standalone]


#73400

FromIan Kelly <ian.g.kelly@gmail.com>
Date2014-06-19 01:37 -0600
Message-ID<mailman.11134.1403163519.18130.python-list@python.org>
In reply to#73394
On Thu, Jun 19, 2014 at 1:23 AM, Ian Kelly <ian.g.kelly@gmail.com> wrote:
> On Thu, Jun 19, 2014 at 12:48 AM, Nicholas Cannon
> <nicholascannon1@gmail.com> wrote:
>> On Thursday, June 19, 2014 1:53:31 PM UTC+8, Nicholas Cannon wrote:
>>> I am making a calculator and i need it to support floating point values but i am using the function isnumeric to check if the user has entered an int value. I need the same for floating point types so i could implement an or in the if statement that checks the values the user has entered and allow it to check and use floating points. If you need the source code i am happy to give it to you. Thank you for your help
>>
>> I am using python 2.7.7 and i have come up with away but there is still possible errors for this. What i did was i this
>>
>> #checks if the user input is an integer value
>> def checkint(a):
>>         if a.isnumeric():
>>                 return True
>>         else:
>>                 if a.isalpha():
>>                         return False
>>                 else:
>>                         return True
>>
>> The parameter a is the users input by the raw_input function. I first test if it is normal int with the isnumeric function. Unfortunately this function picks up the decimal as false. This means if the user inputs a float it has to be false. I then test if this input has any alphabetical characters if it does not the user could have only entered  something like 12.5 oppose to abc.d.
>
> unicode.isalpha does not test if the input has *any* alphabetic
> characters.  It tests if the input is *only* alphabetic characters.
> u'12.5'.isalpha() does return False.  u'abc.d'.isalpha() *also*
> returns False, because the decimal point is not alphabetic.

Incidentally, unicode.isnumeric is probably not what you want either.
According to the docs, it returns "True if there are only numeric
characters in S, False otherwise. Numeric characters include digit
characters, and all characters that have the Unicode numeric value
property, e.g. U+2155, VULGAR FRACTION ONE FIFTH."  So that includes
strings like u'123⅕⅓Ⅷ٤', which is clearly not an integer.  You'd
likely do better with unicode.isdigit, and even then you'd be allowing
for mixed scripts.

[toc] | [prev] | [next] | [standalone]


#73428

FromSturla Molden <sturla.molden@gmail.com>
Date2014-06-19 13:46 +0000
Message-ID<mailman.11151.1403185631.18130.python-list@python.org>
In reply to#73392
<nicholascannon1@gmail.com> wrote:
> I am making a calculator and i need it to support floating point values
> but i am using the function isnumeric to check if the user has entered an
> int value. I need the same for floating point types so i could implement
> an or in the if statement that checks the values the user has entered and
> allow it to check and use floating points. If you need the source code i
> am happy to give it to you. Thank you for your help

It's better to ask forgiveness than ask permission...

You don't have to check anything. If the user enters something that cannot
be coverted to a float, the function float() will raise an exception:

try: 
    x = float(value)
except ValueError:
    # not a float
    pass


Sturla

[toc] | [prev] | [next] | [standalone]


#73446

FromNicholas Cannon <nicholascannon1@gmail.com>
Date2014-06-19 23:14 -0700
Message-ID<c21b1d32-a716-4629-aad6-357b62a8f529@googlegroups.com>
In reply to#73392
Guys i am only a beginner at python most of the stuff you are saying i need to do i dont understand.

[toc] | [prev] | [next] | [standalone]


#73447

FromIan Kelly <ian.g.kelly@gmail.com>
Date2014-06-20 00:22 -0600
Message-ID<mailman.11161.1403245837.18130.python-list@python.org>
In reply to#73446
On Fri, Jun 20, 2014 at 12:14 AM, Nicholas Cannon
<nicholascannon1@gmail.com> wrote:
> Guys i am only a beginner at python most of the stuff you are saying i need to do i dont understand.

All we're saying is that the simplest and most accurate way to
determine whether a string can be converted to an int or a float is to
try converting it and see if it succeeds.  If it fails, it will raise
an exception that you can catch using the try-except syntax.  Here's
what your checkint function might look like:

    def checkint(a):
        try:
            int(a)
        except ValueError:
            return False
        else:
            return True

[toc] | [prev] | [next] | [standalone]


#73455

FromSturla Molden <sturla.molden@gmail.com>
Date2014-06-20 13:16 +0000
Message-ID<mailman.11165.1403270214.18130.python-list@python.org>
In reply to#73446
Nicholas Cannon <nicholascannon1@gmail.com> wrote:

> Guys i am only a beginner at python most of the stuff you are saying i
> need to do i dont understand.

Then listen and try to learn :-)

In C it is customary to do all sorts of sanity checks in advance.
Validating user input is an example. We can call this "to ask permission".
This coding style is often neccessary in C, but not recommended in Python.

In Python we just try to do what we want. If it fails, we get an exception,
e.g. a ValueError. Then we do something with this error instead. We can
call this "to ask forgiveness". If you think you need a validator, you are
very likely thinking "unpythonic". Thus, we don't have to check that the
user typed in a float. We just try to construct a float from the input. If
it fails it wasn't convertible to a float. But you don't have to know that
in advance. All the checks you need to do is already in the function
float(). You don't have to repeat them. float() will succeed or raise an
error. Same for conversion to int: If the user input is convertible to int,
the function int() will do that. If it's not convertible, you get an
exception. Just trap the exception and deal with it when it occurs.

But don't use try/except everywhere! Some exceptions might be due to an
error in your own code, i.e. not in the user input. Those errors you should
not silence, but let your program crash and abort. Then you will know there
is an error in your code. That is what an unhandled exception will do, and
in addition it will tell you where the error is and what it is, so just
leave those exceptions unhandled.

Sturla

[toc] | [prev] | [next] | [standalone]


#73456

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2014-06-20 14:40 +0100
Message-ID<mailman.11166.1403271661.18130.python-list@python.org>
In reply to#73446
On 20/06/2014 14:16, Sturla Molden wrote:
> Nicholas Cannon <nicholascannon1@gmail.com> wrote:
>
>> Guys i am only a beginner at python most of the stuff you are saying i
>> need to do i dont understand.
>
> Then listen and try to learn :-)
>
> But don't use try/except everywhere! Some exceptions might be due to an
> error in your own code, i.e. not in the user input. Those errors you should
> not silence, but let your program crash and abort. Then you will know there
> is an error in your code. That is what an unhandled exception will do, and
> in addition it will tell you where the error is and what it is, so just
> leave those exceptions unhandled.
>

For the OP a very important rule of thumb is never use a bare except, so 
this is right out.

try:
     doSomething()
except:
     WTF()

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com

[toc] | [prev] | [next] | [standalone]


#73461

FromGrant Edwards <invalid@invalid.invalid>
Date2014-06-20 14:28 +0000
Message-ID<lo1gf4$ifp$1@reader1.panix.com>
In reply to#73456
On 2014-06-20, Mark Lawrence <breamoreboy@yahoo.co.uk> wrote:

> For the OP a very important rule of thumb is never use a bare except, so 
> this is right out.
>
> try:
>      doSomething()
> except:
>      WTF()

IMO, that sort of depends on WTF() does. One case where a bare except
is well used is when stdandard output/error are not going anywhere
useful and you want to log the exception and then terminate:

try:
    whatever()
except Exception as e:
    syslog("foobar: terminating due to unhandled exception %s.\n" % e)
    sys.exit(1)    

Alternatively, if you're not at the top level in the call tree,
sometimes it's useful to log an exception but still pass it on up in
case somebody higher up wants to handle it:

def asdf():
    try:
        whatever()
    except Exception as e:
        syslog("Function asdf() terminating due to exception %s.\n" % e)
        raise    
        
-- 
Grant Edwards               grant.b.edwards        Yow! ... or were you
                                  at               driving the PONTIAC that
                              gmail.com            HONKED at me in MIAMI last
                                                   Tuesday?

[toc] | [prev] | [next] | [standalone]


#73464

Fromalister <alister.nospam.ware@ntlworld.com>
Date2014-06-20 15:15 +0000
Message-ID<veYov.84395$0p4.45619@fx29.am4>
In reply to#73461
On Fri, 20 Jun 2014 14:28:52 +0000, Grant Edwards wrote:

> On 2014-06-20, Mark Lawrence <breamoreboy@yahoo.co.uk> wrote:
> 
>> For the OP a very important rule of thumb is never use a bare except,
>> so this is right out.
>>
>> try:
>>      doSomething()
>> except:
>>      WTF()
> 
> IMO, that sort of depends on WTF() does. One case where a bare except is
> well used is when stdandard output/error are not going anywhere useful
> and you want to log the exception and then terminate:
> 
> try:
>     whatever()
> except Exception as e:
>     syslog("foobar: terminating due to unhandled exception %s.\n" % e)
>     sys.exit(1)
> 
> Alternatively, if you're not at the top level in the call tree,
> sometimes it's useful to log an exception but still pass it on up in
> case somebody higher up wants to handle it:
> 
> def asdf():
>     try:
>         whatever()
>     except Exception as e:
>         syslog("Function asdf() terminating due to exception %s.\n" % e)
>         raise

I think that is getting beyond the level of the O.P.
All guide lines may have exceptions but until you have developed enough 
to realise where they can be safely ignored it is best to follow them.



-- 
I was in Vegas last week. I was at the roulette table, having a lengthy
argument about what I considered an Odd number.
		-- Steven Wright

[toc] | [prev] | [next] | [standalone]


#73465

FromIan Kelly <ian.g.kelly@gmail.com>
Date2014-06-20 09:44 -0600
Message-ID<mailman.11170.1403279135.18130.python-list@python.org>
In reply to#73461
On Fri, Jun 20, 2014 at 8:28 AM, Grant Edwards <invalid@invalid.invalid> wrote:
> On 2014-06-20, Mark Lawrence <breamoreboy@yahoo.co.uk> wrote:
>
>> For the OP a very important rule of thumb is never use a bare except, so
>> this is right out.
>>
>> try:
>>      doSomething()
>> except:
>>      WTF()
>
> IMO, that sort of depends on WTF() does. One case where a bare except
> is well used is when stdandard output/error are not going anywhere
> useful and you want to log the exception and then terminate:
>
> try:
>     whatever()
> except Exception as e:
>     syslog("foobar: terminating due to unhandled exception %s.\n" % e)
>     sys.exit(1)

Logging unhandled exceptions and exiting is the job of sys.excepthook,
so I would prefer to replace it with a custom exception handler in
this case.

Also, this isn't an example of a bare except, which is an except
clause with no exception class specified. "except:" and "except
Exception:" are not equivalent. In Python 3, I believe that "except:"
and "except BaseException:" are equivalent. In Python 2 they are not,
because exceptions are also allowed to be old-style classes. In any
case, the advice against bare excepts stems from the fact that bare
excepts will catch things that you usually should not try to catch,
such as SystemExit and KeyboardInterrupt, and so you should normally
specify "except Exception:" in the most general case.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web