Reputation: 21
My problem is when I divide a number like: 10 / 2 → integer / integer.
The result is 5.0 and it is float, but it shouldn't be float. The problem is Python adds 0.0 to every number accept to divide with the second number.
So I want 10/2 be integer.
I tried
x = 10
y = x/2
type(y) == int
It prints false. I want type(y) print the true result although x was a prime or odd number.
Upvotes: 2
Views: 7384
Reputation: 37645
/
gives a floating point result. If you want an integer result, use //
.
The reason it works like this is that if you have something like
function1() / function2()
it is possible to tell the type of the result even if you don't know the types returned by the individual functions.
Edit 1
Note that it has not always been this way. This is a "new" Python 3 behaviour, also available (but not active by default) for Python 2.2 onwards - see PEP 238. Thanks to @Steve314 for pointing this out.
Edit 2
However, it seems that what you are really trying to do is tell if one number goes exactly into another. For this you should use %
(remainder)
print(15 % 5 == 0)
print(16 % 3 == 0)
This prints
True
False
Edit 3
If you want the type of the result to depend on whether the division goes exactly, you would need to do
a // b if a % b == 0 else a / b
Upvotes: 5