python – What is the difference between / and // when used for division?
python – What is the difference between / and // when used for division?
In Python 3.x, 5 / 2
will return 2.5
and 5 // 2
will return 2
. The former is floating point division, and the latter is floor division, sometimes also called integer division.
In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division
, which causes Python 2.x to adopt the 3.x behavior.
Regardless of the future import, 5.0 // 2
will return 2.0
since thats the floor division result of the operation.
You can find a detailed description at PEP 238: Changing the Division Operator.
Python 2.x Clarification:
To clarify for the Python 2.x line, /
is neither floor division nor true division.
/
is floor division when both args are int
, but is true division when either of the args are float
.
python – What is the difference between / and // when used for division?
//
implements floor division, regardless of your type. So
1.0/2.0
will give 0.5
, but both 1/2
, 1//2
and 1.0//2.0
will give 0
.
See PEP 238: Changing the Division Operator for details.