[Tutor] checking if a variable is an integer?

Marilyn Davis marilyn at pythontrainer.com
Tue May 31 23:54:59 CEST 2011


You'll like:

>>> isinstance(1, int)
True
>>> isinstance(1.5, int)
False

There are infinite primes.  Proofs abound on the Internet.

But, that's not the problem.

Yes, the problem is possible for any finite number.  And it's a nice
little practice problem.  Remember that you can skip the testing for all
even numbers.  They aren't prime.  That'll cut your run time in half,
about.

Marilyn Davis



On Tue, May 31, 2011 2:40 pm, Rachel-Mikel ArceJaeger 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)
>
>
> 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-rep
>> resents-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
>>
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list