[Tutor] checking if a variable is an integer?

Noah Hall enalicho at gmail.com
Tue May 31 23:51:00 CEST 2011


On Tue, May 31, 2011 at 10:36 PM, Rachel-Mikel ArceJaeger
<arcejaeger at gmail.com> wrote:
> Isn't one of the unsolved millenium prize problems one that includes the
> ability to find all of the prime numbers? I'm not sure if your program is
> possible if the input number is large.
> But to check if a number x is an int, just do this:
> x == int(x)

As a note to the OP, this won't work without exception catching.
>>> 2 == int(2)
True
>>> 2 == int("fish")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'fish'


Of course, you can use the built-in string method isdigit() for this,
for example -
>>> "fish".isdigit()
False
>>> "2".isdigit()
True
>>> "2.0".isdigit()
False
>>> "2000".isdigit()
True


More information about the Tutor mailing list