Exponents are mathematical operations that represent the number of times a number (the base) is multiplied by itself. This short and straight-to-the-point article shows you 2 different approaches to calculating exponents in Python. Without any further ado, let’s get our hands dirty with code.
Using the ** operator
Like many other programming languages, Python uses the **
operator for exponentiation. The example below shows you how to use the **
operator to calculate the result of 10 to the power of 3:
output = 10 ** 5
print(output)
Output:
100000
10
is the base, and 5
is the exponent.
Here’s another example with the exponent is a float:
result = 10 ** 3.25
print(result)
Output:
1778.2794100389228
Using the math.pow() function
Besides the **
operator, you can use the pow()
function of the math
module to get the job done.
Example:
import math
result1 = math.pow(2, 4)
result2 = math.pow(2, 1.5)
print('result1 =', result1)
print('result2 =', result2)
Output:
result1 = 16.0
result2 = 2.8284271247461903
Note that the pow()
function always returns a float. In the example above, you get 16.0
instead of 16
.