Here are four ways to calculate the exponent in Python:
Method 1: Using the ** operator
The ** operator is the simplest way to calculate the power of a number.
Visual Representation
Example
# Printing the result of 5 raised to the power of 3
print(5 ** 3)
Output
125
Method 2: Using pow() function
The built-in pow() function takes two arguments, the base and the exponent, and returns the value of the base raised to the power of the exponent.
Visual Representation
Example
# Printing the result of 5 (base) raised to the power of 3 (exponent)
print(pow(5, 3))
Output
125
Let’s pass the negative exponent to the pow() function and see the output.
print(pow(5, -3))
Output
0.008
Here 5 to power -3 means 1 / 125 = 0.008.
Method 3: Using math.pow() function
You can also use the math.pow() function, which works similarly to pow(), but always returns a float.
Visual Representation
Example
import math
# Calculating the result with base 5 and exponent 3
print(math.pow(5, 3))
print(math.pow(5, -3))
Output
125.0
0.008
Method 4: Using exp()
If you want to calculate the natural exponential value (e^x), you can use math.exp().
In this context, e represents Euler’s number (approximately 2.71828), and x is the exponent provided to the function.
Visual Representation
Example
import math
# Printing the value of e raised to the power of 5
print(math.exp(5))
Output
148.4131591025766
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.