Kanishka Ganguly
Kanishka Ganguly

Reputation: 1298

Python - computed value is always 0.0

I have a basic loop as follows:

for x in range(81,346):
    print float(((x - 81)/(346-81))*100)
    # DO STUFF

The thing is, the output I get is 0.0 for all values. I checked to see that x-81 is giving the correct output. I also replaced 346-81 as 265. But for some reason, all output is being given as 0.0.
Any suggestions as to what is going wrong?

Upvotes: 1

Views: 76

Answers (2)

zvone
zvone

Reputation: 19382

Python 2 uses integer division on integers. It was a bad idea and Python 3 fixed it. To have the (better) behaviour from future, put this in the beginning of your py file:

from __future__ import division

Upvotes: 3

timgeb
timgeb

Reputation: 78770

You are performing integer division. Change 81 to 81.0 or cast the numerator or denominator to float.

Upvotes: 4

Related Questions