How can I divide two numbers in Python 2.7 and get the result with decimals?
I don't get it why there is difference:
in Python 3:
>>> 20/15
1.3333333333333333
in Python 2:
>>> 20/15
1
Isn't this a modulo actually?
This question is related to
python
python-2.7
python-3.3
division
"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:
float(20)/15 #1.33333333
In Python 3, /
is float division
In Python 2, /
is integer division (assuming int
inputs)
In both 2 and 3, //
is integer division
(To get float division in Python 2 requires either of the operands be a float, either as 20.
or float(20)
)
In Python 2.x, make sure to have at least one operand of your division in float
. Multiple ways you may achieve this as the following examples:
20. / 15
20 / float(15)
Source: Stackoverflow.com