On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
> > I never thought that you can use a float and a integer to look if
> > the number is a integer.
>
> You can't.
What? Of course you can.
def is_integer(x):
"""Return True if x is an integer."""
try:
return 1.0*x == int(x)
except (TypeError, ValueError):
return False
And in use:
>>> is_integer("12")
False
>>> is_integer(2.3)
False
>>> is_integer(2.0)
True
>>> is_integer(2)
True
The multiplication by 1.0 is not actually needed, but it doesn't hurt.
[thinks more carefully...] Actually it does hurt:
>>> is_integer(Decimal(2))
False
So although you *can* use float and int to determine if a value is an
integer, it's best to avoid the float.
--
Steven D'Aprano
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor