Python 3 reference · Built-in Functions
Python pow() Function
Raise a number to a power, like base ** exp. With a third argument it computes the result modulo a number efficiently.
Python 3 Since 3.0
Syntax
pow(base, exp, mod=None)
Parameters
| Parameter | Description |
|---|---|
base |
The number to raise. |
exp |
The exponent. |
mod optional |
If given, return (base ** exp) % mod, computed efficiently. Default: None |
Return value
The result; an int, float or complex depending on the inputs.
Examples
print(pow(2, 10), 2 ** 10)
print(pow(2, -1), pow(9, 0.5))
Output
1024 1024 0.5 3.0
print(pow(7, 128, 13)) # fast, no huge number built
print(pow(3, -1, 7)) # modular inverse: 3 * 5 % 7 == 1
Output
3 5
Good to know
The three-argument form is what cryptography and hashing code uses: it never computes the huge intermediate
number. A negative exponent with mod gives the modular inverse (Python 3.8+).
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.8 | Negative exponents with mod compute modular inverses; arguments can be passed by keyword. |
Related
abs()· Return the absolute value of a number: its distance from zero, so negative numbers become positive.divmod()· Divide two numbers and return the quotient and the remainder together as a tuple: (a // b, a % b).round()· Round a number to a given number of decimal places. Halfway values round to the nearest even number (banker's rounding).- Python Math · tutorial
- Python Operators · tutorial