how to check if a value is a floating point or not
Ben Finney
ben at benfinney.id.au
Thu Jun 19 03:19:44 EDT 2014
Nicholas Cannon <nicholascannon1 at 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
More information about the Python-list
mailing list