Python Floor Division — A Complete Guide to the // Operator

In Python, the double-backslash operator (//) is the floor division operator. Floor division means dividing and rounding down to the nearest integer.

For example:

>>> 7 // 3
2

The physical interpretation of the floor division is about sharing quantities evenly. For example, given 7 apples and 3 eaters, how many full apples does each person get? The answer is 7 // 3 = 2.

Illustrating floor division by sharing apples to people

In Python, the following equality holds for floor division:

a // b == math.floor(a / b)

In this guide, you are going to learn everything you need to know about floor division in Python.

Floor Division in Python

In Python, floor division divides two numbers and rounds the result down to the nearest integer.

Before taking a deeper look at the floor division, let’s quickly remind ourselves what is division, and what math.floor() function does in Python.

Regular Division in Python

In Python, you can divide two numbers with the backslash division operator (/).

For example:

>>> 4 / 3
1.3333333333333333

Division in Python works the same way as division works in mathematics.

Math.floor() Function in Python

In Python, there is a built-in math module that comes with useful mathematical tools for calculations.

One of the built-in functions of the math module is the math.floor(). This function takes a numeric input and floors the result down to the nearest integer.

Flooring a number to the next integer

For example:

>>> from math import floor
>>> floor(2.25)
2

>>> floor(-1.25)
-2

Now you understand the concepts of dividing and flooring numbers in Python. Next, let’s jump into details about floor division in Python.

Floor Division

Floor division is an operation in Python that divides two numbers and rounds the result down to the nearest integer. The floor division happens via the double-backslash (//) operator.

r = a // b

Where:

  • r is the result of the floor division
  • a is the dividend
  • b is the divisor.

You can think of floor division as a regular division combined with math.floor() function call.

Notice how the floor division rounds any number down to the nearest integer. For example, 4.99 will still be rounded down to 4.

Here is an example of a floor division:

>>> 7 // 2
3

Compare this to a regular division

>>> 7 / 2
3.5

Here you can compare the results to see that this is indeed the case:

>>> import math

>>> math.floor(10 / 3)
3
>>> 10 // 3
3

>>> math.floor(4 / 3)
1
>>> 4 // 3
1

Floor Division with Negative Numbers

Floor division is also possible using negative numbers.

In the case of negative numbers, the result is still rounded down to the nearest integer. What might confuse you is that rounding down a negative number means going away from zero. For example, -3.2 is floored down to -4.

Here is an example:

>>> -10 // 3
-4

With a regular division, -10 / 3 would return -3.33… but with a floor division, this number is rounded down to the nearest negative integer, that is, to -4.

Floor Division with Floats

Floor division works with floats in Python.

When floor-dividing floats, the result is a float that represents the nearest integer.

Here are some examples:

>>> 10.0 // 2.5
4.0

>>> 5.0 // 3
1.0

>>> 6 // 4.0
1.0

Floor Division and Modulo in Python

In mathematics, modulo is a concept that is heavily related to floor division. In short, modulo means the remainder in the division between two numbers. In other words, you can count the number of leftovers with it.

To calculate modulo in Python, use the percentage operator (%).

Example. Given 7 apples and 3 eaters, you can calculate the number of apples each eater gets using the floor division:

>>> 7 // 3
2

The result is 2.

Now let’s calculate the total number of apples being shared among the group. This is trivial. Multiply the number of apples per person by the number of eaters:

>>> 3 * 2
6

The total number of full apples shared is 6. However, the total number of apples is 7. This means 1 apple will be leftover and is not going to be eaten.

This example describes one way to calculate the number of leftovers. But if you are only interested in the number of leftovers, you can directly calculate it using modulo.

Example. Given 7 eaters and 3 apples, what is the number of leftover apples?

Answer. Let’s calculate the answer using modulo:

>>> 7 % 3
1

The number of leftovers is 1.

To further understand the concept of modulo, please check this article.

In Python, the floor division and the modulo are related by this equation:

a = b * (a // b) + (a % b)

Where:

  • a is the dividend.
  • b is the divisor.

For example, let’s verify this equation holds with the 7 apples and 3 eaters example:

7 = 3 * (7 // 3) + (7 % 3)
7 = 3 * 2 + 1
7 = 7

Now you understand the concepts of floor division and modulo in Python. Next, let’s have a look at a built-in function that calculates both.

Floor Division and the divmod() Function

In Python, the built-in divmod() function calculates both the floor division and the modulo between two numeric values.

Syntax:

r = divmod(a, b)

Where:

  • r is the result as a tuple. This tuple has the floor division result and the remainder given by the modulo.
  • a is the dividend.
  • b is the divisor.

Example. Given 7 eaters and 3 apples, how many full apples does each eater get and how many apples are leftover?

Answer. Let’s calculate these numbers using the built-in divmod() function:

>>> napples, nleftovers = divmod(7, 3)
>>> napples
2
>>> nleftovers
1

Floor Division Precedence

In Python, the floor division operator // has the same precedence level as multiplication (*), division (/), and modulo (%).

This means that if you multiply, and then floor-divide, the multiplication is performed first, and then the floor division, and vice versa.

But if you for example subtract two numbers and then floor-divide, the floor-division operation will precede.

Let’s see an example:

>>> 3 * 4 // 5 - 6
-4

To understand how this result is calculated, you can insert parenthesis around the terms in the correct precedence order.

>>> ((3 * 4) // 5) - 6
-4

Here is the step-by-step calculation of the above:

  • 3 * 4 // 5 – 6
  • ((3 * 4) // 5) – 6
  • (12 // 5) – 6
  • 2 – 6
  • -4

Now you know about floor division, and how to use it in Python.

Last, but not least, let’s take a look at an advanced use case for the floor division. In this case, advanced does not mean hard, but rather uncommon.

Advanced Use of Floor Division

Did you know you can make your custom objects support floor division too in Python? This is possible via a special method called __floordiv__().

The __floordiv__() Method in Python

The floor division in Python divides two numbers and rounds the result down to the nearest integer.

The way it works under the hood is that a numeric type implements a special method __floordiv__(). Then, whenever you call // between two objects the __floordiv__() method gets called.

In Python, you can call the __floordiv__() method directly as well.

For example:

>>> 7 // 3
2

>>> (7).__floordiv__(3)
2

As you can see, both expressions produced the same result. This is because the first expression gets converted to the second expression. In other words, these calls are equivalent to one another.

Now here is where it gets interesting.

Let’s create a custom class NumStr. This class represents integer values as strings:

class NumStr:
    def __init__(self, value):
        self.value = value

Let’s create two NumStr objects:

n1 = NumStr("7")
n2 = NumStr("3")

Then, let’s floor-divide n1 by n2:

n1 // n2

This results in an error.

Traceback (most recent call last):
  File "<string>", line 8, in <module>
TypeError: unsupported operand type(s) for //: 'NumStr' and 'NumStr'

The error message reveals that NumStr objects do not support floor division. This error makes sense. How would the custom type have any idea about floor-dividing strings objects?

But, as it turns out, you can make the NumStr object support floor division.

Previously, you learned whenever you call //, you are actually calling the__floordiv__() method. This method is implemented somewhere in the class of the object. For example, int objects support floor division, because the int class has implemented the __floordiv__() method.

What is cool about these special methods, such as __floordiv__(), is you can implement these into your custom class. In other words, you can make your custom objects support floor division in Python.

For example, let’s write an implementation for the __floordiv__() method into the NumStr class:

class NumStr:
    def __init__(self, value):
        self.value = value
    
    def __floordiv__(self, other):
        n1 = int(self.value)
        n2 = int(other.value)
        result = n1 // n2
        
        return NumStr(str(result))

In this example implementation, the __floordiv__() method works such that it:

  1. Takes the numeric string value from itself. (a when calling a // b)
  2. Takes the numeric string value from another object. (b when calling a // b)
  3. Converts both to integers.
  4. Performs a floor division between the integers values.
  5. Converts the result into a string and creates a new NumStr object of it.

Now you can perform a floor division between two NumStr objects!

For example:

n1 = NumStr("7")
n2 = NumStr("3")

res = n1 // n2

print(res.value)

Output:

2

Awesome. Now you understand how to make a custom class support floor division.

By the way, if you do not like the fact that you have to call object.value to see the result, implement the __str__() method that directly returns the value when printing:

class NumStr:
    def __init__(self, value):
        self.value = value
    
    def __floordiv__(self, other):
        n1 = int(self.value)
        n2 = int(other.value)
        result = n1 // n2
        
        return NumStr(str(result))
    
    def __str__(self):
        return self.value

Now it is possible to simply call:

print(NumStr("7") // NumStr("3"))

Output:

2

Summary

Today you learned about floor division and the // operator in Python.

To recap, floor division means dividing two numbers and rounding the number down to the nearest integer.

In Python, the following equality holds:

a // b = math.floor(a / b)

The physical interpretation of the floor division is that given a group and items, how many parts each member of the group gets when the items are shared between the group.

For example, when handing out 10 slices of pizza to a group of 4 fairly, each person gets 2 full slices of pizza. This number is obtainable using the floor division.

>>> 10 // 4
2

You can also make your custom classes support floor division by implementing the __floordiv__() method.

Thanks for reading.

Make sure you check out the list of must-have tools and resources for developers!

Happy coding!

Read Also