Python divmod(): Return Quotient and Remainder — Syntax, Integers vs Floats, Negative Values, Relationship to // and %, Pitfalls, and Practical Examples > dev

Skip to content

Entire search within the site

👈Go back dev

Python Python divmod(): Return Quotient and Remainder — Syntax, Integers vs F…

page info

name Goposu datetime⏰ 25-10-11 03:20 hit👁️ 16 comment💬 0

text

Python divmod(): Return Quotient and Remainder — Syntax, Integers vs Floats, Negative Values, Relationship to // and %, Pitfalls, and Practical Examples

Python divmod(): Compute quotient and remainder in one call

The built-in divmod() function returns a tuple (q, r) where q is the quotient and r is the remainder. It is a concise, fast alternative to separate // and % operations, and works with integers, floats, and numeric types that implement floor-division and modulo.

Syntax

divmod(a, b)  # -> (quotient, remainder)

Parameters: a (dividend) and b (divisor) are numeric values. b must be non-zero for integers; with floats, a zero divisor raises ZeroDivisionError as well.

Returns: A tuple. For integers: (int, int); for floats: (float, float).

Quick examples

print(divmod(10, 3))     # (3, 1)
print(divmod(10, 5))     # (2, 0)
print(divmod(-10, 3))    # (-4, 2)  (floor-division behavior)
print(divmod(10.0, 3.0)) # (3.0, 1.0)

How divmod() relates to // and %

divmod(a, b) is equivalent to (a // b, a % b), but performs both in one step. For integers, Python’s division is floor-based: the quotient q satisfies q = floor(a / b), and the remainder r follows a == b*q + r with 0 <= r < |b|.

a, b = -10, 3
q, r = divmod(a, b)
print(q, r)             # -4 2
print(a == b*q + r)     # True

Integers vs floats

  • Integers: Quotient is floor-divided; remainder is non-negative and less than |b| (unless b is negative—see sign rules).
  • Floats: Uses floating-point arithmetic; both outputs are floats and subject to rounding errors.
  • Large integers: Python supports arbitrary-precision ints; divmod() scales to very large values.
print(divmod(10, -3))    # (-4, -2)  (remainder has same sign as divisor)
print(divmod(7.5, 2.0))  # (3.0, 1.5)

Common use cases

  • Time and unit conversion: Split seconds into minutes and seconds; bytes into KB and remainder.
  • Indexing math: Convert linear index to (row, col).
  • Packing/unpacking: Compute chunk counts and leftover items.
# 1) Time split
mins, secs = divmod(367, 60)         # (6, 7)

# 2) Grid coordinates
idx, width = 37, 8
row, col = divmod(idx, width)        # (4, 5)

# 3) File chunks
size, chunk = 10241, 4096
chunks, leftover = divmod(size, chunk)  # (2, 49)

Pitfalls and caveats

  • Zero divisor: divmod(a, 0) raises ZeroDivisionError (int or float).
  • Sign rules: With negative values, remember Python’s floor division. The remainder’s sign follows the divisor; verify a == b*q + r if unsure.
  • Float precision: Floating-point results may have tiny rounding errors; prefer integers when exactness matters.
  • Non-numeric types: Passing unsupported types raises TypeError unless the type defines compatible // and % behavior.
try:
    divmod(5, 0)
except ZeroDivisionError as e:
    print(e)

Advanced notes

  • Decimal/Fraction: With decimal.Decimal, // and % semantics apply; prefer integer divisors to avoid context surprises. For fractions.Fraction, results follow exact rational arithmetic.
  • NumPy arrays: Use numpy.divmod for element-wise operations; built-in divmod is scalar-only.
  • Performance: divmod() computes quotient and remainder together, often faster than calling // and % separately on large integers.

FAQ

Does the remainder always have the same sign as the divisor?
Yes for integers in Python; ensure 0 <= r < |b| when b > 0. For negative b, r is non-positive.
Is divmod(a, b) exactly (a // b, a % b)?
Yes, it returns those two results together, with the same semantics.
Should I use floats with divmod?
It works, but be mindful of rounding; prefer integers for precise partitioning.

Related keywords

Python divmod, quotient and remainder, floor division, modulo, negative division, integer arithmetic, unit conversion

👍good0 👎nogood 0

comment list 0

There are no registered comments.

이미지 목록

전체 19건 1 페이지
게시물 검색
Copyright © https://goposu.com All rights reserved.
View PC version