Division in Python 2.7. and 3.3

PythonPython 2.7Python 3.3Division

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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)

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErzsebetView Question on Stackoverflow
Solution 1 - PythonbgusachView Answer on Stackoverflow
Solution 2 - PythonmhlesterView Answer on Stackoverflow
Solution 3 - PythonwoozykingView Answer on Stackoverflow
Solution 4 - PythonBryanView Answer on Stackoverflow