# Python divmod()

Filed Under: Python

Python divmod() function is used to perform division on two input numbers. The numbers should be non-complex and can be written in any format such as decimal, binary, hexadecimal etc.

## Python divmod()

Python `divmod()` syntax is:

``````
divmod(a, b)
``````

The output is a tuple consisting of their quotient and remainder when using integer division.

For integer arguments, the result is the same as (a // b, a % b).

For floating point numbers the result is (q, a % b), where q is usually (math.floor(a / b), a % b). In any case q * b + a % b is very close to a.

If a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

## Python divmod() example with integers

``````
# simple example, returns (a // b, a % b) for integers
dm = divmod(10, 3)
print(dm)

x, y = divmod(10, 3)
print(x)
print(y)

dm = divmod(0xF, 0xF)  # hexadecimal
print(dm)
``````

Output:

``````
(3, 1)
3
1
(1, 0)
``````

## Python divmod() example with floats

``````
# floats, returns usually (math.floor(a / b), a % b)
dm = divmod(10.3, 3)
print(dm)

dm = divmod(11.51, 3)
print(dm)

dm = divmod(-11.51, 3)
print(dm)
``````

Output:

``````
(3.0, 1.3000000000000007)
(3.0, 2.51)
(-4.0, 0.4900000000000002)
``````

Notice that in case of floating points, the `q * b + a % b` is very close to `a` in some cases.

## divmod() with complex numbers

If we pass complex numbers as argument, we will get `TypeError`.

``````
dm = divmod(3 + 2J, 3)
``````

Output: `TypeError: can't take floor or mod of complex number.`

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

close
Generic selectors
Exact matches only
Search in title
Search in content