Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 divmod()

Python3 divmod() Function

Python3 Built-in Functions Python3 built-in function

The Python divmod() function takes two numeric (non-complex) arguments and returns a tuple containing the quotient and remainder (a // b, a % b).

In Python 3.x this function does not support complex numbers.

Function syntax

divmod() takes two arguments, usually two numbers, and returns a tuple of two values. The first value is the quotient of the first argument divided by the second (i.e. the integer part), and the second is the remainder.


divmod(a, b)

Parameter Description:

If both arguments a and b are integers, the result is equivalent to (a // b, a % b)。

If either argument is a float, the result is equivalent to (q, a % b), where q is usually math.floor(a / b) but may be 1 less; nevertheless q * b + a % b is very close to a.

If the remainder of a % b is not 0, the sign of the remainder matches argument b: if b is positive the remainder is positive, and if b is negative the remainder is negative, and 0 <= abs(a % b) < abs(b)。

Example

divmod

(

7

,

2

)

(

3

,

1

)

divmod

(

8

,

2

)

(

4

,

0

)

divmod

(

8

,

2

)

(

4

,

0

)

divmod

(

3

,

1.3

)

(

2.0

,

0.3999999999999999

)

Application scenarios of divmod()

divmod() is very useful in scenarios such as time conversion and pagination calculations.

1. Time conversion: for example, converting a total number of seconds into hours, minutes, and seconds:

Example

total_seconds

=

3661

hours

,

remainder

=

divmod

(

total_seconds

,

3600

)

minutes

,

seconds

=

divmod

(

remainder

,

60

)

print

(

f

"{hours}h {minutes}m {seconds}s"

)

 

Output: 1h 1m 1s

2. Pagination: in a pagination system, divmod() can compute the total number of pages and the number of records on the last page:

Example

total_items

=

101

items_per_page

=

10

pages

,

remainder

=

divmod

(

total_items

,

items_per_page

)

if

remainder:

    pages +

=

1

print

(

f

"Total pages: {pages}"

)

 

Output: Total pages: 11

Notes on the divmod() function

The second argument of divmod() cannot be 0, otherwise a ZeroDivisionError exception is raised.

The types of the quotient and remainder returned by divmod() depend on the input argument types. If the inputs are integers, the quotient and remainder are integers too; if they are floats, the results are floats.

Python3 Built-in Functions Python3 built-in function