pow()
Raise to a power — with an optional third argument for efficient modular exponentiation used in cryptography and modular arithmetic.
Demo
pow(a, b) is the same as a**b. The three-argument pow(a, b, m) computes a**b mod m without ever materializing the intermediate a**b — critical when the exponent is large (cryptography, hashing). Negative exponents on integers return floats in the two-arg form; the three-arg form supports negative exp too (3.8+), returning the modular inverse.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| base | int | float | yes | The base. |
| exp | int | float | yes | The exponent. Negative on integers returns a float unless mod is given. |
| mod | int | no (None) | When given, the result is base**exp mod mod, computed efficiently. All three must be integers; negative exp requires base coprime with mod (3.8+, gives modular inverse). |
Return value
int | float — base to the power of exp. If mod is given, the result is taken modulo mod — computed by fast modular exponentiation without materializing base**exp.
Common patterns
ciphertext = pow(plaintext, e, n)
root = pow(x, 0.5)
inv = pow(a, -1, m) # a × inv ≡ 1 (mod m)
byte_max = pow(2, 8) - 1
Examples
Pitfalls
pow(3, 10**6) % 97
pow(3, 10**6, 97)
pow(2, -3)
pow(2, -1, 13) # 7 — the inverse of 2 mod 13
pow(2.0, 10, 13)
pow(int(2.0), 10, 13)
pow(0, -1)
pow(0, -1) if base != 0 else default
When to use
- Modular arithmetic in cryptography, hashing, algorithms
- Powers with a computed exponent (readability over **)
- Modular inverse via `pow(a, -1, m)` — Python 3.8+
- When you want an explicit function call in a math-heavy pipeline
- Simple constant powers → the ** operator is clearer
- Powers of two → `1 << n` is idiomatic
- Cases where operator overloading matters (e.g. numpy) → operator preserves broadcasting
Notes
FAQ
Python follows the "combinatorial" convention: 0**0 = 1. This matches how empty products and Taylor series expansions are defined, and how most math libraries behave. It is a choice — some mathematicians prefer "undefined" — but Python commits to 1.