I’m (very) new to all of this programming stuff and I need help with a program I’m making in Python 3. It’s designed, at the moment, to find how many numbers between 1 and 10 are divisible by 5. This is my approach:
def five():
a = 0
b = 0
c = 0
while a <= 9:
a = a + 1
b = a / 5
if type(b) == int and b is not 0:
c = c + 1
else:
pass
print c
In this case it’s printing “6”.
The problem is, well, as you might already know, in Python the number 1.0 is not an integer. The only thing I want is to make Python know all numbers with a 0 after the dot are integers, or find an interactive programming language who does, or find another approach.
Thanks!
Asking for the
type()of a value in Python is not going to tell you whether it is a round integer or not. The resulting type of a calculation doesn’t change type depending on the answer. (But in Python 2, the type of the answer in division depends on the type of the inputs. In Python 3, the type after/is alwaysfloat, while the type after//depends on the type of the inputs.)To test for an integer divisible by 5, use the modulo operator:
Also, avoid using the
isoperator with integers. Useb != 0to compare with zero, instead ofb is not 0(see Python “is” operator behaves unexpectedly with integers for the gory details).