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

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

Leave a Comment