[Tutor] checking if a variable is an integer?

Rachel-Mikel ArceJaeger arcejaeger at gmail.com
Tue May 31 23:40:59 CEST 2011


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)


Rachel


On Tue, May 31, 2011 at 2:38 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:

> On Tue, May 31, 2011 at 11:30 PM, Joel Goldstick
> <joel.goldstick at gmail.com> wrote:
> >
> >
> >
> http://stackoverflow.com/questions/1265665/python-check-if-a-string-represents-an-int-without-using-try-except
> >
> > def RepresentsInt(s):
> >
> >     try:
> >         int(s)
> >
> >         return True
> >     except ValueError:
> >
> >         return False
> >
> >>>> print RepresentsInt("+123")
> >
> > True
> >>>> print RepresentsInt("10.0")
> >
> > False
> >
>
> For strings, that works, but not for integers:
>
> >>> int(10.0)
> 10
>
> And if you want to check if one number is divisible by another, you're
> not going to call it on strings.
>
> A better way is to use the modulo operator, which gives the remainder
> when dividing:
>
> >>> a = 6
> >>> a % 3
> 0
> >>> a % 4
> 2
>
> So, if the remainder is zero the left operand is divisible by the right
> one.
>
> Hugo
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110531/7e006c1f/attachment-0001.html>


More information about the Tutor mailing list