Reputation: 41
m = 10
x = 5
val = 1
print(type(val))
for i in range(1, x+1):
val = (val * (m + i)) / (i)
print(type(val))
print(val)
Here initially val
is of type int
but in the loop it is getting converted to float
although I am performing integer by integer division. Why is it so?
Upvotes: 1
Views: 3776
Reputation: 160377
It is specified in the Semantics for True division in PEP 238
:
True division for
int
s andlong
s will convert the arguments tofloat
and then apply afloat
division. That is, even2/1
will return afloat
(2.0
), not anint
. Forfloat
s andcomplex
, it will be the same as classic division.
So an automatic conversion is performed when an int
is found. Note that this is the default behaviour in Python 3. In python 2 you'll need to import
from __future__
in order to have similar results.
Upvotes: 2
Reputation: 3203
You have to use: //
val = (val * (m + i)) // (i)
And your val will remain being an integer
The behavior of /
was changed with this: https://www.python.org/dev/peps/pep-0238/
The operator
module docs give also a hint about the separation between true division
(returning a float) and floor division
which returns the floor and therefore an int
https://docs.python.org/3/library/operator.html
Upvotes: 3