[Tutor] checking if a variable is an integer?
Hugo Arts
hugo.yoshi at gmail.com
Tue May 31 23:38:16 CEST 2011
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
More information about the Tutor
mailing list