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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With