Python Reference ยท Built-in Functions
Python pow() function
Reference for Python pow(): raise numbers to a power, use the three-argument modular form, negative exponents, and the differences from ** and math.pow.
The built-in pow() function raises a number to a power. With two arguments, pow(base, exp) is equivalent to base ** exp. With three arguments, pow(base, exp, mod) computes (base ** exp) % mod efficiently, without ever building the huge intermediate number. That form is the workhorse of cryptography and number theory.
The result type follows the usual numeric rules: integers stay integers when the exponent is non-negative, anything involving a float is a float, and a negative integer exponent gives a float.
pow(2, 10) # 1024 pow(2, -1) # 0.5 pow(3, 200, 7) # 2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
pow(base, exp) pow(base, exp, mod=None)
| Name | Description |
|---|---|
base |
The number to raise. |
exp |
The exponent. |
mod |
Optional modulus. When given, all three arguments must be integers (and mod non-zero). |
Return value: base to the power exp, reduced modulo mod when mod is given. The result of the three-argument form has the sign of mod (it is in 0 <= r < mod for positive mod).
Raises: ZeroDivisionError for 0 raised to a negative power, or mod equal to zero. ValueError if a modular inverse does not exist (negative exp with mod). TypeError for non-integers with three arguments.
Usage notes
- Same as
**for two arguments, except thatpowis a function, so you can pass it tomap()and similar tools. - Use the three-argument form for big exponents.
pow(a, b, m)runs in time proportional to the number of bits inb, whilea ** b % mfirst builds a gigantic number. - Negative exponents with
mod(Python 3.8+) compute the modular inverse:pow(3, -1, 11)is 4 because3 * 4 % 11 == 1. It raisesValueErrorif the base and modulus share a factor. - Integer powers are exact.
pow(10, 30)has all its digits, unlike a float. - Negative base with fractional exponent returns a
complexnumber in Python 3, not an error:pow(-8, 1 / 3)is complex. - Differences from
math.pow().math.powalways returns a float and raisesValueErrorwherepowmight return a complex number; for exact integers usepowor**. 0 ** 0is1in Python.- Custom classes support
pow()through__pow__()(and__rpow__());__pow__receives the optional modulus as a third parameter. - Precedence.
-2 ** 2is-4because**binds tighter than unary minus;pow(-2, 2)is4.
Related
abs(),divmod(),round(),sum()- Lessons: Arithmetic operators, Numbers, Math and random