Integer division uses Python's // operator to produce an integer result rather than the floating-point result produced by /. section 3.2.1 section 4.5
The main rules are:
- 5 / 2 produces 2.5, while 5 // 2 produces 2. section 3.2.1
- Use // when a calculation should return an integer instead of retaining a fractional part. section 4.5
- Integer arithmetic otherwise produces integers, while operations involving a float produce a float. section 4.7
- Python integers can grow as large as available memory allows, so integer division is not restricted to small values. section 3.2.1
Compare division operators
5 / 2 # 2.5\n5 // 2 # 2\n5 % 2 # 1\n\nThe first expression keeps the fractional result; the second returns an integer; the third returns the remainder. section 3.2.1
x = 5 + 2 - 3 * 2 x 1 5 / 2 2.5 #1 5 // 2 2 #2 5 % 2 1 2 ** 8 256 1000000001 ** 3 1000000003000000003000000001 #3 #1 Float result using <kbd>/</kbd> #2 Result forced to integer using<kbd>//</kbd> #3 Integer size limited only by available memory
Run the compact arithmetic listing to compare /, //, and % with their displayed results. section 3.2.1
