How to use exponents in Python?
In this tutorial, we learn how to use exponents in Python. Raising a number to the second power is a little more complicated than normal multiplication. Simply put, exponent is the number of times that the number is multiplied by itself. We can use three different ways in Python to do that. Let's see what those ways are.
Table of contents
- What is the exponent?
- Using ** operator for exponents
- Using pow() function for Python exponent
- Using math.pow() function for Python exponents
- Closing thoughts
What is the exponent?
In Mathematical terms, an exponent refers to a number that is placed as a superscript of a number. It says how many times the base number is to be multiplied by itself. The Exponentiation is written as mⁿ and pronounced as "m raised to the power of n". Here "n" is the exponent and "m" is the base. It means m is to multiplies by m, n number of times. We cannot solve exponents like we normally do multiplication in Python.
Surely, for 2^3 we can multiply 2, 3 times and get the result but it will fail when we are dealing with bigger numbers. So, we need a proper way to solve the exponents.
Using exponent operator in Python
The exponent operator or the power operator works on two values. One is called the base and the other is the exponent. As explained earlier, the exponent tells the number of times the base is to be multiplied by itself.
m ** n
Here, the exponent operator raises it's second variable to the power of it's first variable.
m = 3 n = 2 p = m ** n print ("On solving the exponent, we get ", p)
On solving the exponent, we get 8
Using pow() function for Python exponents
Python has a built-in function that is useful for calculating power: pow(). It accepts two parameters which are a base and an exponent. It returns the modulus of the result. The result will always be a positive integer.
Here, "m" is the base (the number raised to the power of the exponent) and "n" is the exponent (the number to which the base is raised).
m = 2 n = 3 p = pow(m,n) print ("The answer is: ", p)
The answer is: 8
Using math.pow() function for Python exponents
Python has another function math.pow() that allows you to solve exponents. It also accepts two parameters: a base and an exponent. The main difference between pow() and math.pow() is that math.pow() converts both variables into the floating point and always returns a float.
m = 2 n = 3 p = math.pow(m,n) print ("The answer is: ", p)
The answer is: 8.0
Doing Mathematics in Python is easy, but calculating exponents in Python is a little tricky. We have learnt how to use exponents in Python. But remember in Python, it will return a zero division error if we raise 0 to any power. Python also has other mathematical operators, and one can read about them here.