Division in Python

The double-frontslash // operator performs integer division and the single-frontslash / operator performs float division. An example for integer division is 40//11 = 3. An example for float division is 40/11 = 3.6363636363636362.

>>> # Python 3
>>> 40//11
3
>>> 40/11
3.6363636363636362

A crucial lesson you need to master as a programmer is “division in Python”. What does it mean to divide in Python? What are the different uses and subtleties? Many beginners and even intermediate coders do not learn these subtle differences—and it costs them hours, even days of debugging their code.

So you may ask: how you divide in Python?

There are two types of division: integer division and float division.

  • Integer division divides two numbers and returns a whole number.
  • Float division divides two numbers and returns a decimal “floating point” value.

⭐ Many people get confused about the acceptable use of operators when dividing two numbers. Especially when they apply division that unexpectedly returns an integer and not, as expected, a float. For example, Java uses integer division that skips the remainder, i.e., no decimal values, so it will always return a whole number. This is a common source of errors.

Python division depends on the used operators.

  • The use of regular division uses the single front-slash / operator. This operator will result in a decimal value.
  • Floor division uses the double front-slash // operator. This operator will result in a whole number, or integer value being given.
  • Then we can go a step further and use the Modulo Operator (percent symbol) % which gives you a remainder value or a zero. 

Let’s explore these three division operators in more detail next.

Floor Division //

Python 2.x per default divides two integers using integer division, also known as floor division because it applies the floor function after the regular division to “round it down”. Python 2 evaluates the expression 5/2 to 2. However, the single front-slash for floor division “/” is depreciated and from Python 2.2 onwards, you should use the double front-slash operator for floor division. For example, the result of 5//2 is 2.

An example of floor division is noted in the Python 3 code listed below:

>>> x = 60 // 12
>>> print(x)
5

So we see that when we need a whole number generated in our code to accomplish particular tasks we will use this floor division operator //.

Float Division /

In Python 3, the single front-slash “/” is a float division operator that returns a float value as a result. For example, the expression 10/4 returns 2.5 instead of 2, and 4/2 returns 2.0 instead of 2.

>>> # Python 3
>>> 10/4
2.5
>>> 4/2
2.0

Integer Division /

Be careful to use the most updated type of Python available. For example, Python 2.0 returns an integer instead of a float value for the / operator. Also when we perform division in Python we want to be careful what value we divide by. We find that if we divide by a whole number, it will round to an integer.

>>> 10 / 90
0

Overriding Division in Python

In Python 3.x, you can overload the division using the __floordiv__ and __truediv__ magic methods. The former corresponds to the double frontslash // operator that returns an integer and the latter to the single frontslash / operator that returns a float. Note that a common error arises from trying to override the __div__ magic method instead.

The following example overrides both division operators of a custom class Number.

class Number:
    def __init__(self, x):
        self.x = x

    def __floordiv__(self, other):
        return self.x // other.x

    def __truediv__(self, other):
        return self.x / other.x


my = Number(42)
your = Number(21)

print(my/your)
# 2.0

print(my//your)
# 2

Modulo Operator %

The Modulo Operator % is a special division operator that calculates the remainder of an integer division.

Example: It can be used to find out leap years. We can set up a calendar program. A leap year happens every fourth year. It has 29 days in February instead of 28 days and has 366 days in the year. It occurs in 1996, 2000, 2004, 2008… 2020 and so on every 4 years. So we can find out if a year is a leap year by simply dividing it by four. If the answer for the remainder is zero, it is a leap year.

The Modulo operator is referred to as the remainder from the division of the first argument to the second argument. Working with this operator we find that the numbers are first converted into their common type.

A zero division error is caused if the right argument is zero. These arguments can be floating-point numbers. We find that the absolute value for the result is smaller than the second operand. And the result of using the modulo operator will always yield the same sign as the second operand or zero. To see the results of using the Modulo operators you can follow the code written below.   

year_input = int(input("enter a year: "))
if year_input % 4 == 0:
    print("Remainder is zero!", year_input, "is a leap year!")
else:
    print(year_input, "is not a leap year!")

If we enter 2004 in the code above we will get a response that says the remainder is zero. So 2004 will be a leap year. However, if we were to put 2021 into the equation,  the answer to the input would be "2021 is not a leap year!"

NumPy Division Further Reading

One degree of difficulty further with the use of division in Python is the use of Numpy. Numpy is a general-purpose tool that allows for the processing of many numbers arranged in arrays.

When you have multiple division processes going on, you can accelerate it significantly by using NumPy division. It also performs element-wise division that works on multi-dimensional NumPy arrays like so:

import numpy as np

# Create 2D lists
a = [[1, 2, 3],
     [4, 5, 6]]

b = [[2, 4, 6],
     [8, 10, 12]]


# Convert lists to 2D NumPy arrays
a = np.array(a)
b = np.array(b)

# Divide the 2D arrays
print(a / b)

The result of this division operation printed to the shell is an array of floats:

[[0.5 0.5 0.5]
 [0.5 0.5 0.5]]

Related Article: The Ultimate Guide to NumPy

Summary

So to sum up, we have taken a journey on our look at the use of division in Python from the simplest formula with simple division by using the operator / to the more complex use of division with Python by using the operator // to give an integer value. We could have also accomplished this with the two different arguments. We can use the float() and int() functions. We will use float() to give us a decimal value and int() to give us a whole number.

Then we moved on to the use of the Modulo Operator. This allowed us to use the remainders of the division process. These are incorporated into our code to perform specific functions. Then these functions were used to figure out when Leap Years will occur for our calendar program. And finally, we arrive at the culmination of the use of division in Python.

We implement Numpy to perform many computations fast. This allows us to use big data so multiple computations in the division of many numbers can be done quickly and efficiently.

Arithmetic Operators

Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers.

OperatorNameDescriptionExample
+AdditionCalculating the sum of the two operands3 + 4 == 7
SubtractionSubtracting the second operand from the first operand4 - 3 == 1
*MultiplicationMultiplying the first with the second operand3 * 4 == 12
/DivisionDividing the first by the second operand3 / 4 == 0.75
%ModuloCalculating the remainder when dividing the first by the second operand7 % 4 == 3
//Integer Division, Floor DivisionDividing the first operand by the second operand and rounding the result down to the next integer8 // 3 == 2
**ExponentRaising the first operand to the power of the second operand2 ** 3 == 8