Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

().is_integer() not working

Whats wrong with this code:

n = 10
((n/3)).is_integer()

I do not understand why I cannot set n = any number and check if it is an integer or not.

Thanks for your help!

python 2.7.4

error:

Traceback (most recent call last):
  File "/home/userh/Arbeitsfläche/übung.py", line 2, in <module>
    print ((n/3)).is_integer()
AttributeError: 'int' object has no attribute 'is_integer'
like image 934
aaaa Avatar asked Jun 18 '13 13:06

aaaa


3 Answers

The reason you get this error is because you divide the integer 10 by 3 using integer division, getting the integral number 3 in the form of an int instance as a result. You then try to call the method is_integer() on that result but that method is in the float class and not in the int class, just as the error message says.

A quick fix would be to change your code and divide by 3.0 instead of 3 which would result in floating point division and give you a float instance on which you can call the is_integer() method like you are trying to. Do this:

n = 10
((n/3.0)).is_integer()
like image 173
Sebastian Ärleryd Avatar answered Nov 05 '22 05:11

Sebastian Ärleryd


You are using Python 2.7. Unless you use from __future__ import division, dividing two integers will return you and integer. is_integer exists only in float, hence your error.

like image 6
Morwenn Avatar answered Nov 05 '22 05:11

Morwenn


the other answers say this but aren't very clear (imho).

in python 2, the / sign means "integer division" when the arguments are integers. that gives you just the integer part of the result:

>>> 10/3
3

which means that in (10/3).is_integer() you are calling is_integer() on 3, which is an integer. and that doesn't work:

>>> (3.0).is_integer()
True
>>> (3).is_integer()
AttributeError: 'int' object has no attribute 'is_integer'

what you probably want is to change one of the numbers to a float:

>>> (10/3.0).is_integer()
False

this is fixed in python 3, by the way (which is the future, and a nicer language in many small ways).

like image 4
andrew cooke Avatar answered Nov 05 '22 05:11

andrew cooke