[Tutor] exceptions problem

Steven D'Aprano steve at pearwood.info
Sat Sep 11 12:22:47 CEST 2010

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."""
        return 1.0*x == int(x)
    except (TypeError, ValueError):
        return False

And in use:

>>> is_integer("12")
>>> is_integer(2.3)
>>> is_integer(2.0)
>>> is_integer(2)

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))

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

More information about the Tutor mailing list