Reputation: 23
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
Upvotes: 2
Views: 80
Reputation: 532418
When both operands are integers in Python 2, a/b
is the same as a//b
, meaning you get integer division. 50 / 1000
is 0 in that case (with a remainder of 50, as you can see from the return value of divmod(50, 1000)
).
Upvotes: 2
Reputation: 396
if you use python 2.X above result came's if use python 3.x result is
Python 3.4.3 (default, Jul 28 2015, 18:24:59)
[GCC 4.8.4] on linux
>>> a = 50/1000*100
>>> a
5.0
>>> a = 50/1000.0*100
>>> a
5.0
>>>
Upvotes: 0
Reputation: 6631
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.
Upvotes: 3