简体   繁体   中英

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?

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

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

True division for int s and long s 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 float s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM