79

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?

Alex.K.
  • 3,342
  • 13
  • 38
  • 44
Erzsebet
  • 813
  • 1
  • 7
  • 7

4 Answers4

126

In python 2.7, the / operator is integer division if inputs are integers.

If you want float division (which is something I always prefer), just use this special import:

from __future__ import division

See it here:

>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>

Integer division is achieved by using //, and modulo by using %

>>> 7 % 2
1
>>> 7 // 2
3
>>>

EDIT

As commented by user2357112, this import has to be done before any other normal import.

Martijn Courteaux
  • 63,780
  • 43
  • 187
  • 279
bgusach
  • 13,019
  • 10
  • 44
  • 61
  • 3
    It's worth noting that future statements have to appear before any other code in a module, particularly before non-future imports. Also, `import __future__` doesn't work. – user2357112 supports Monica Jan 23 '14 at 19:04
  • Nice. Using `__future__` is almost always the recommended way – woozyking Jan 23 '14 at 19:08
  • Thanks! I too always prefer that float division :) – Erzsebet Jan 23 '14 at 19:08
  • Why is this preferable to `float(3)/float(2)`? – dumbledad Jan 16 '17 at 11:23
  • 1
    @dumbledad, it is more readable, concise and intuitive – bgusach Jan 16 '17 at 11:26
  • 1
    Interesting - I do not find it more intuitive. If I know that `/` is integer division and the result has decimals I would be taken by suprise, and the `from __future__ import division` may be more than a screenful away. – dumbledad Jan 16 '17 at 11:37
  • 2
    Well, it is somehow subjective, but for me, coming from other languages, it was confusing that dividing 3/2==1. Many people may agree, because float division is the default in python 3 – bgusach Jan 16 '17 at 12:08
52

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))

mhlester
  • 21,143
  • 10
  • 49
  • 71
17

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)
woozyking
  • 3,949
  • 1
  • 19
  • 28
11

"/" 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

Bryan
  • 1,510
  • 11
  • 12