Search code examples
pythonpython-3.4integer-division

Integer division in Python 3 - strange result with negative number


I am new to Python, and I am learning operators right now. I understood that:

  • The / operator is used for floating point division and
  • // for integer division.

Example:

7//3 = 2

And 7//-3=-3. Why is the answer -3?

I am stuck here.


Solution

  • // is not integer division, but floor division:

    7/-3  -> -2.33333...
    7//-3 -> floor(7/-3) -> floor(-2.33333...) -> -3
    

    PEP 238 on Changing the Division Operator:

    The // operator will be available to request floor division unambiguously.

    See also Why Python's Integer Division Floors (thanks to @eugene y) - Basically 7//-3 is -7//3, so you want to be able to write:

    -7 = 3 * q + r
    

    With q an integer (negative, positive or nul) and r an integer such that 0 <= r < 3. This only works if q = -3:

    -7 = 3 * (-3) + 2