Four ways to get an integer result when dividing two integers in Python

In Python, dividing two integers results in a float being returned, even if the result doesn’t have a remainder:

>>> 15 / 3
5.0

Here are four ways you can do the same calculation, but with a return value that is an integer.

Casting to an integer

>>> int(15 / 3)
5

An obvious choice, and the one most developers will turn to right away in pretty much any programming language.

Ground division

>>> 15 // 3
5

This operator does the usual division, but returns only the integer part of the result.

Rounding

>>> round(15 / 3)
5

The round() function can be used to round a float value using an additional parameter. If no parameter is used, the result is rounded to the integer value only.

divmod()

>>> divmod(15, 3)
(5, 0)

The divmod() function returns a tuple, containing the quotient and remainder, both presented in integer format.