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'
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()
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With