I am new to Python, and I am learning operators right now. I understood that:
- The
/
operator is used forfloating point division
and //
forinteger division
.
Example:
7//3 = 2
And 7//-3=-3
. Why is the answer -3
?
I am stuck here.
I am new to Python, and I am learning operators right now. I understood that:
/
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.
//
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
//
is the operator for floor division.
This means that after the division is completed the "floor" function is applied (the value retrieved from the division is rounded down to the nearest integer regardless of whether the decimal part is greater or less than .5)
As for your example, be careful to note that for negative answers the floor division operator will still be rounding down (e.g. -5/2 --> -2.5 --> -3).