Search code examples
pythonfloating-pointsemanticsinteger-division

Python - Divide only worked when used floating point for divisor


Why is it that my code only worked when I turned the divisor into a float?

a = 50/1000.0*100

When I did the below, it returned a 0.

a = 50/1000*100

Solution

  • 50/1000 is 0 in python 2.x because division of integers assumes you want integer results. If you convert either the numerator or denominator to a float you will get the correct behavior. Alternatively you can use

    from __future__ import division

    to get the python 3.x semantics.