-4

I have noticed that Python 2.7 uses '/' as integer division.

>>> print 1/2
0

Since Python is a dynamically-typed language, this was a bit of a surprise. Is there a specific reason as to why Python's '/' operator was defined this way?

subwaymatch
  • 1,020
  • 10
  • 11

3 Answers3

3

Python 2's / operator is either integer or floating point, depending on the types of the operands.

>>> print 1.0/2
0.5
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
3

Language design "why"s are hard questions to answer in general, though Guido could probably tell you the answer here. I suspect it's simply because "that's the way it was done". More specifically, because that's how division works in C, which is in many ways the parent language of not only Python but most other modern imperative languages. Of course, C got it from B and BCPL, and if you keep tracing, you'll find that this particular division behavior goes all the way back to Fortran.

However, the behavior in question is not "always integer division". Just as in C and Fortran and so on, Python 2's / is not integer division unless its operands are both integers:

>>> 1/2
0
>>> 1.0/2
0.5

This fact means if the arguments are expressions instead of literals, you can't tell whether the result is going to be truncated or not, which can lead to confusion. This ambiguity is the reason that the operator was changed in Python 3 to always do float division, and the // operator was introduced to always do truncating division. In Python 2.2+, those changes are available to be imported from the __future__ pseudo-module as the feature division.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
2

It's just a historical accident. They did it that way, probably because that's how it commonly worked in other mainstream languages at the time. Many of those other languages were statically typed, and the difference in expectation was not immediately appreciated.

But there's no greater reason that can help explain your surprise. This behaviour of the division operator is now regarded as a mistake by the Python maintainers, and was changed for Python 3; the only reason it's still that way in Python 2 to avoid changing the behaviour of existing code (see https://www.python.org/dev/peps/pep-0238/).

You can add this line to the top of your Python files:

from __future__ import division

to redefine the division operator across the whole module so that it always performs "true" division (with // as the operator for integer division). I basically put this in any module where I use division.

Ben
  • 68,572
  • 20
  • 126
  • 174