liveBook · Manning

Integer division

As explained in The Quick Python Book, Fourth Edition

Integer division is division whose result is truncated to an integer value.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines // and demonstrates its output beside / and %, without developing implementation internals.
Examples
Demonstrates 5 / 2, 5 // 2, and 5 % 2 with outputs 2.5, 2, and 1.
What it assumes
Assumes familiarity with variables and arithmetic expressions while distinguishing Python's / and // operators.
What you can do after
Apply integer division via Python's // operator when a calculation must return an integer.
How it connects
Connects integer division with arithmetic expressions, floating-point division, modulus, operator precedence, integers, and floats.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.