How to test if a variable has a natural number?

Piet van Oostrum piet at
Sat Jun 21 14:03:06 CEST 2003

>>>>> pythonguy at (Anand Pillai) (AP) wrote:

AP> You can still use types. Just add a check for LongTypes also.
AP> from types import *

AP> def natural(num):

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

It is better to do the type test first.

>>> natural(1+1j)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in natural
TypeError: cannot compare complex numbers using <, <=, >, >=

Piet van Oostrum <piet at>
Private email: P.van.Oostrum at

More information about the Python-list mailing list