Division in Python 2.7. and 3.3 [duplicate] Division in Python 2.7. and 3.3 [duplicate] python python

Division in Python 2.7. and 3.3 [duplicate]


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 / 23>>> from __future__ import division>>> 7 / 23.5>>>

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

>>> 7 % 21>>> 7 // 23>>>

EDIT

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


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. / 1520 / float(15)