Python pow() Function
The pow()
method computes the power of a number by raising the first argument to the second argument.
Syntax
pow(number, power, modulus)
pow() Parameters
Python pow()
function parameters:
Parameter | Condition | Description |
---|---|---|
number | Required | The base value that is raised to a certain power |
power | Required | The exponent value that raises number |
modulus | Optional | Divides the result of number paused to a power and finds the remainder: number^power% modulus |
pow() Return Value
Python pow()
function returns:
number^power
fornumber
raised to a certainpower
number^power % modulus
if the optionalmodulus
argument is specified1
if the value ofpower
is0
0
if the value ofnumber
is0
If the exponent (second argument) is negative, then the pow()
function returns a float result.
Examples
Example 1: Calculate Power of a Number
If two arguments are specified, the pow(x, y)
method returns x
to the power of y
.
x = pow(5, 2)
print(x) # Output: 25
output
25
Example 1: Calculate Power of a Negative Number
x = pow(-2, 3)
print(x) # Output: -8
output
-8
Example 2: Calculate Power of a Float Number
x = pow(2.5, 2)
print(x) # Output: 25
output
Example 3: Calculate Power of a Complex Number
x = pow(3+4j, 2)
print(x) # Output: (-7+24j)
output
(-7+24j)
Example 4: Calculate Power of a Number and Negative Exponent
x = pow(2, -2)
print(x) # Output: 0.25
output
0.25
Example 5: Use **
power operator to compute the Power of a Number
x = 10**2
print(x) # Output 100
output
100
Example 6: Calculate Power of a Number using Modulus
If all the three arguments are specified, pow(x, y, z)
function returns x
to the power of y
, modulus z
.
x = pow(5, 2, 3)
print(x) # Output: 1
output
1
You can achieve the same result using the power operator **
and modulus operator %
:
x = 5**2%3
print(x) # Output: 1
output
1
Example 7: Calculate the Modular Inverse with pow() function
In modular arithmetic, the modular inverse of a number a
modulo m
is a number b
such that (a * b) % m = 1
. This means that b
is the multiplicative inverse of a
under modulo m
.
The modular inverse exists only if a
and m
are coprime (i.e., their greatest common divisor is 1
).
Starting with Python 3.8, the pow()
function can directly calculate the modular inverse when provided with a negative exponent because raising a number to a negative power is equivalent to finding its multiplicative inverse modulo m
.
For example, let's calculate the modular inverse of 38
modulo 97
. The result is 23
, which verifies that (38 * 23) % 97 = 1
.
# Only Python 3.8 and later
result = pow(38, -1, 97)
print(result) # Output: 23
output
23