Walter
Walter

Reputation: 41

Automatic int to float conversion

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

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160377

It is specified in the Semantics for True division in PEP 238:

True division for ints and longs will convert the arguments to float and then apply a float division. That is, even 2/1 will return a float (2.0), not an int. For floats and complex, 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

mementum
mementum

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

Related Questions