In this tutorial, you’ll learn how to perform floor division in Python. You’ll use Python’s // operator, the floor function from Python’s math module, and more – with code examples.

We’ll start with an overview of arithmetic operators in Python and learn how the floor division operator // works. Then, we’ll learn how to use other equivalent methods including functions from the math and operator modules to perform floor division.

Let’s get started…

Arithmetic Operators in Python

In Python, you can use arithmetic operators to perform simple arithmetic operations on numbers the int and float data types. These operators act on operands (the numbers) and return the result of the operation.

<img alt="Arithmetic-Operators-in-Python" data- data-src="https://kirelos.com/wp-content/uploads/2022/11/echo/Arithmetic-Operators-in-Python.png" data- height="400" src="data:image/svg xml,” width=”800″>

The following table summarizes the arithmetic operators in Python and how they work:

Operator Syntax Result
Addition ( ) num1 num2 Returns the sum of num1 and num2
Subtraction (-) num1-num2 Returns the difference between num1 and num2
Multiplication (*) num1*num2 Returns the product of num1 and num2
Exponentiation (**) num1**num2 Returns the result of num1 raised to the power of num2; num1num2
Division (/) num1/num2 Returns the result when num1 is divided by num2 – including the fractional part
Floor division (/) num1//num2 Returns the quotient when num1 is divided by num2
Modulo (%) num1 % num2 Returns the remainder when num1 is divided by num2

Let’s take a few examples that use these arithmetic operators. You can try out these examples in a Python REPL or in Geekflare’s online Python editor.

>>> num1 = 18
>>> num2 = 5

>>> num1   num2
23

>>> num1 - num2
13

>>> num1 * num2
90

>>> num1 ** num2
1889568

In this example, num1 is 18 and num2 is 5. The division operation num1/num2 returns the result including the fractional part.

The number 5 goes into 18 three times leaving a remainder of three. Therefore, the floor division operation, num1//num2, gives the quotient 3, while the modulo operator gives the remainder – also 3 in this case.

>>> num1/num2
3.6

>>> num1//num2
3

>>> num1 % num2
3

This should give you an idea of how the division, floor division, and modulo operators work. Next, we’ll learn about the floor division operator in detail.

⚠️ In Python 2, the division operation (/) truncates the result to the nearest integer—similar to the floor division operation in Python 3. This tutorial discusses how the floor division operation works in Python 3.x.

Floor Division Using the // Operator

<img alt="Floor-Division-Using-the-Operator" data- data-src="https://kirelos.com/wp-content/uploads/2022/11/echo/Floor-Division-Using-the-Operator.png" data- height="400" src="data:image/svg xml,” width=”800″>

Consider a division operation with a dividend and a divisor. In num1/num2, num1 is the dividend and num2 is the divisor. To perform floor division of num1 and num2, use num1//num2.

The floor division operator (//) returns the quotient of the division operation—as an integer or a floating point number—depending on the data types of the operands.

The floor division operator does not ensure that the answer is always an integer. If either the dividend (num1) or the divisor (num2) is a float then the result of num1//num2 is a float. Here are a few examples.

>>> 18.0//5
3.0
>>> 10.0//4
2.0
>>> 15//4.0
3.0

If you need the result to be an integer, then you need to explicitly cast it into an integer using int() function:

>>> int(18.0//5)
3
>>> int(10.0//4)
2
>>> int(15//4.0)
3

What Happens Under the Hood?

When you use the floor division operator //, the special method (also called dunder method) __floordiv__() gets called. Therefore, you can also use the __floordiv__() method on any integer or floating point number, as shown below:

num1 = 18
num2 = 5
num1.__floordiv__(num2)
# Output: 3

Floor Division Using operator.floordiv()

<img alt="Floor-Division-Using-operator.floordiv" data- data-src="https://kirelos.com/wp-content/uploads/2022/11/echo/Floor-Division-Using-operator.floordiv.png" data- height="400" src="data:image/svg xml,” width=”800″>

💡 To perform floor division in Python, you can also use the floordiv() function in the operator module.

Python’s operator module contains the definitions of efficient functions that can perform all arithmetic operations. Therefore, to perform floor division, you can also use the floordiv() function from the operator module – instead of the // operator.

Using the floordiv() function from the operator module is equivalent to using the floor division operator.

>>> import operator
>>> operator.floordiv(18,5)
# Output: 3
>>> operator.floordiv(12,5.0)
# Output: 2.0

Floor Division Using math.floor()

How Does the Floor Function Work?

In math, the floor() function takes in any real number x as the input and returns an integer (result). This result is the largest integer that is less than or equal to the real number x.

To understand this better, let us take a few examples and visualize these numbers on a number line.

Example 1: Consider the number 2.3. The largest integer that is less than or equal to 2.3 is 2; so floor(2.3) will return 2.

<img alt="python-floordivision-tutorial-ex1" data- data-src="https://kirelos.com/wp-content/uploads/2022/11/echo/9-1500×844.png" data- height="422" src="data:image/svg xml,” width=”750″>

Example 2: You can apply the same definition when working with negative numbers as well. Consider the number -1.7. The largest integer that is less than or equal to -1.7 is -2; so floor(-1.7) will return -2.

<img alt="python-floordivision-tutorial-ex2" data- data-src="https://kirelos.com/wp-content/uploads/2022/11/echo/10-1500×844.png" data- height="422" src="data:image/svg xml,” width=”750″>

Let’s verify the above results using the floor() function from the math module.

>>> from math import floor
>>> floor(2.3)
2
>>> floor(-1.7)
-2

To perform floor division, you can call the floor() function with num1/num2 as the argument. As it truncates or rounds down the result to the nearest integer, it’s equivalent to the floor division operation.

You can explicitly import the floor() function from the math module, as shown:

from math import floor
num1 = 18
num2 = 5
floor(num1/num2)
# Output: 3

Alternatively, you can as well import only the math module and then access the floor() function using math.floor().

import math
num1 = 18
num2 = 5
math.floor(num1/num2)
# Output: 3

Unlike the floordiv() function from the operator module and the floor division operator //, using math.floor(num1/num2) ensures that the result is an integer. This method makes the code readable and eliminates the type-casting step.

import math
num1 = 18.0
num2 = 5
math.floor(num1/num2)
# Output: 3

Examples of Floor Division in Python

<img alt="Examples-of-Floor-Division-in-Python" data- data-src="https://kirelos.com/wp-content/uploads/2022/11/echo/Examples-of-Floor-Division-in-Python.png" data- height="400" src="data:image/svg xml,” width=”800″>

Let’s conclude our discussion with a practical example: Binary search. ✅

📑 Binary search is an efficient search algorithm that lets you search for a target element through sorted arrays in O(log n) time, where n is the size of the array.

This algorithm works by dividing the search interval into half at each step. This is done depending on whether the midpoint of the interval matches the target (search ends as match is found!) or is less than or greater than the target. As the size of the array is reduced by half at each step, the midpoint does not always evaluate to an integer.

itemlist = [5,7,18,21,34,45]
item = 7

Consider the following implementation of the binary search algorithm. The function binary_search() takes in a number (item) and a list (itemlist) and searches for the occurrence of the item in itemlist.

  • If the item is found, the function returns the index at which item occurs.
  • Else, it returns None.
def binary_search(item, itemlist):
    # get the list size
    listsize = len(itemlist) - 1
    # start at the two ends of the list
    lowerIdx = 0
    upperIdx = listsize

    while lowerIdx  itemlist[midPt]:
            lowerIdx = midPt   1
        else:
            upperIdx = midPt - 1

    if lowerIdx > upperIdx:
        return None

This implementation is functionally correct except that we have not accounted for the midPt not evaluating to an integer as the search proceeds.

binary_search(item,itemlist)

If we call the function, we run into a TypeError stating that the list indices must be integers or slices, not float.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
----> 1 binary_search(item,itemlist)

 in binary_search(item, itemlist)
     12 
     13         # if item is found, return the index
---> 14         if itemlist[midPt] == item:
     15             return midPt
     16         # otherwise get the next midpoint

TypeError: list indices must be integers or slices, not float

We modify the function definition to use the floor division operator:

def binary_search(item, itemlist):
    # get the list size
    listsize = len(itemlist) - 1
    # start at the two ends of the list
    lowerIdx = 0
    upperIdx = listsize

    while lowerIdx  itemlist[midPt]:
            lowerIdx = midPt   1
        else:
            upperIdx = midPt - 1

    if lowerIdx > upperIdx:
        return None

 The function returns the index at which the item 7 is found, which is index one.

binary_search(item,itemlist)
# Output: 1

Conclusion

I hope this tutorial helped you understand how to perform floor division in Python. Here’s a summary of the different methods you’ve learned:

  • In Python, a operator b performs the operation defined by the operator with a and b as the operands and returns the result of the operation.
  • You can use Python’s floor division operator //; a//b returns the quotient of the division operation a/b.
  • Alternatively, you can use the equivalent floordiv() function defined in Python’s operator module with the syntax: operator.floordiv(a,b) to get the result of a//b.
  • All the above methods return the quotient but the data type can be a float or an int depending on the values of a and b. So you’ll have to cast the return value to an integer.
  • The floor() function from Python’s math module can also be used to perform floor division: math.floor(a,b) is equivalent to a//b and returns an integer. When you want the result to be an integer, consider using the floor function from the math module.

Next, learn how to work with defaultdict in Python. 👩🏽‍💻