How to Use Integer Division in Python

Learn to divide and ignore the remainder

How to Use Integer Division in Python
Photo by Dan Meyers on Unsplash

What is Integer Division?

Integer division is an arithmetic operation where division is performed, but the remainder is discarded leaving us with just an integer.

In other programming languages, the combination of division plus something akin to a “floor” function is used to achieve similar results.

Here’s an example in JavaScript:quotient = 8 / 3;
whole_number = Math.floor(quotient);console.log(whole_number); // prints 2

Having to round-down a normal division operation may not be particularly difficult, but it can be annoying and inconvenient. Fortunately, Python has us covered with the integer division operator.

Integer Division in Python

Many popular languages such as JavaScript, Java, and PHP use the double forward slash // as a comment operator. However, in Python this simple operator is in fact used for integer division.

There isn’t too much to say, so let’s take a look at an example.a = 8
b = 3quotient = a / b
whole_number = a // bprint(quotient, type(quotient))
print(whole_number, type(whole_number))

The above code block would output the following:2.6666666666666665 <class 'float'>
2 <class 'int'>

Notice that integer division not only removes the decimal (rounding down), but also returns an actual integer data type.

Conclusion

These little optimizations and efficiencies are a true delight in Python. Commit integer division to memory and be sure to pull it out of the toolbox the next time you need to ignore the remainder!


Please share your experiences, questions, and feedback below. Follow Code 85 for more plain language programming guides. Thanks for reading!

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe