Python abs(), divmod(), and pow()
Learn three core numeric built-ins: abs() for magnitude, divmod() for quotient and remainder together, and pow() for exponentiation and modular arithmetic.
Basic
Some numeric tasks have small, dedicated built-ins.
abs() gives an absolute value,
divmod() returns quotient and remainder together, and
pow() performs exponentiation and can also perform modular exponentiation.
The Numbers lesson already teaches ordinary arithmetic operators and
round(). This lesson focuses only on these three built-ins and the distinct problems they solve.
abs(): get an absolute value
abs(number) returns the absolute value of a number. For real numbers, that means the non-negative magnitude. For a complex number, it returns the number's magnitude.
Output
Ready to run.
divmod(): get quotient and remainder together
divmod(a, b) returns a pair containing the quotient and remainder from integer-style division. For integers, it is equivalent to the pair
(a // b, a % b).
Output
Ready to run.
Negative operands follow Python's floor-division rules
divmod() follows the same floor-division and remainder rules as
// and
%. The identity
q * b + r == a helps you interpret the returned pair.
Output
Ready to run.
pow(): exponentiation
pow(base, exp) performs exponentiation. With two arguments it has the same arithmetic meaning as
base ** exp.
Output
Ready to run.
pow() with a modulus
pow(base, exp, mod) computes the power and then reduces the result modulo
mod. For integer arguments, this form is useful when you need a modular result without first materializing the full power.
Output
Ready to run.
A modular inverse
For integer arguments, Python also allows a negative exponent in the three-argument form when the base has an inverse modulo
mod. For example, the result below is a value whose product with 3 leaves remainder 1 modulo 11.
Output
Ready to run.
Choosing the right built-in
Use
abs() when you need magnitude,
divmod() when you need quotient and remainder as a pair, and
pow() when exponentiation is the operation. Use the three-argument form of
pow() when the modulus is part of the problem.
Quick check
Quick check
Which built-in returns the quotient and remainder together for two integers?
result = (29, 6)
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.