How to test if a variable has a natural number?

Anand Pillai pythonguy at Hotpop.com
Sat Jun 14 10:46:54 EDT 2003


You can still use types. Just add a check for LongTypes also.

from types import *

def natural(num):

    if num>=0 and (type(num) is IntType or type(num) is LongType):
        return 1
    else:
        return 0


>>> natural(1L)
1
>>> natural(100000000000L)
1
>>> natural(2.0)
0
>>> natural(-1.0)
0

~Anand 
danb_83 at yahoo.com (Dan Bishop) wrote in message news:<ad052e5c.0306121556.46c82564 at posting.google.com>...
> Alexander Schmolck <a.schmolck at gmx.net> wrote in message news:<yfsznknjn5w.fsf at black132.ex.ac.uk>...
> > pythonguy at Hotpop.com (Anand Pillai) writes:
> > 
> > > How about this...
> > > 
> > > from types import *
> > > 
> > > def natural(num):
> > >     if num>0 and type(num) is IntType:
> > >         return 1
> > >     else:
> > >         return 0
> > 
> > Nope. 
> > 
> > >>> natural(1L)
> > 0
> 
> How about...
> 
> def natural(num):
>    return num > 0 and num == long(num)
> 
> ?




More information about the Python-list mailing list