chwps
chwps

Reputation: 23

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

Upvotes: 2

Views: 80

Answers (3)

chepner
chepner

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

Najeeb Choudhary
Najeeb Choudhary

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

Chad S.
Chad S.

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

Related Questions