What is integer division?

Question

What is integer division? Does this occur in both Python 2.7 and Python 3? How can I account for it?

Answer

Integer division is the division of one integer by another in which the resulting number is truncated (ie. decimal places are dropped), such that the quotient is also an integer. This is the default behavior in Python 2.7, but not Python 3. For example, 3 / 2 returns 1 in Python 2.7, but 1.5 in Python 3.

If we want to obtain a decimal result in Python 2.7, we can convert one of the integers to a float using float() or by multiplying by a floating point value:

print(3 / 2)  # prints 1

print(float(3) / 2)  # prints 1.5
print((1.0 * 3) / 2)  # prints 1.5

Conversely, in Python 3, if we want to use integer division instead of the standard float division, we can use the // operator:

print(3 / 2)  # prints 1.5

print(3 // 2)  # prints 1
1 Like