English

FAQ: Why is an integer value returned, instead of a real number, when dividing two integers when working in Python?

Question

Why is an integer value returned, instead of a real number, when dividing two integers when working in Python?

Answer

In Python, dividing two integer values yields an integer result. For example:

Code:
1.0 / 2.0 --> 0.5
1.0 / 2 --> 0.5
1 / 2.0 --> 0.5
1 / 2 --> 0


Therefore, if at least one operand is a real number, a real result is returned.

In the future, Python will switch to always yielding a real result. To force an integer division operation, use the special '//' integer division operator. That behavior can be used now by importing it 'from the future':

Code:
from __future__ import division


The following is the resulting behavior:

Code:
1 / 2 --> 0.5
4 / 2 --> 2.0
1 // 2 --> 0
4 // 2 --> 2


This applies to the Python Window in ArcMap, the ArcMap Field Calculator, the Geoprocessing Calculate Field tool (with the Python parser selected), and any Python IDE, for example, PythonWin or IDLE.