Python | A function that calculates the power of a number

Let us take a look at how to code for this program. We have some built-in functions and other than that we will also take a look at how to solve this using function along with the concept of recursion and iteration.

Method 1: Using the basic function and dynamic values

def power_of(b,e):
    power = b ** e
    print('The power of %0.1f to %0.1f is %0.1f'%(e ,b,power))

b = int(input("Enter the value of base: "))
e = int(input("Enter the value of exponent: "))

power_of(b,e)

Output:

Enter the value of base: 2
Enter the value of exponent: 12
The power of 12.0 to 2.0 is 4096.0

Explanation:

Here we used a simple function, we passed the arguments taken by the user and then used the ** operator to calculate the power. This is the most basic method.

Method 2: Using the iterative approach

def calc_pow(base,power):
  P=1
  for i in range(1, power+1):
    P=P*base
  return P
 
base,power=3,4
print(calc_pow(base,power))

Explanation:

Here we use the for loop to iterate over the defined range. Here we multiply the base by itself equal to the power. So in the above code, the base is 3 and the power is 4. So we will multiply 3 by itself 4 times.

Method 3: Using the recursive approach

def power(n, e):
    if e == 0:
        return 1
    elif e == 1:
        return n
    else:
        return (n*power(n, e-1))
n = 4
p = 2
print(power(n, p))

Explanation:

Here we give the function’s definition; it has two parameters. We will return 1 if the exponent or power is 0. Return n, the number itself, if the exponent or power equals 1. If not, multiply the current value and then repeatedly invoke the power(n,e) function, decrementing e (exponent/power) by 1 each time. Finally, we displayed the output, which is the number’s intended power, last.

Method 4: Using the pow() function

print(pow(9, 2))

Explanation:

Simply we used the pow() function. This is the built-in function.

Method 5: Using the numpy library

import numpy as np

base = 2
exponent = 3
result = np.power(base, exponent)
print(result) 

Explanation:

We installed the numpy library and used the power function of this library. In this function, we have passed two arguments namely base and exponent.

Method 6: Using the exp() function

import math

result = math.exp(math.log(2) * 3)
print(result) 


Explanation:

In this method, we used the exp() of the math library. In that, we used the log function and assigned the base as 2 and the power is equal to 3. The output of this is passed on to the exp() function and the result is stored in the result variable.

Here is the end of this article. We learned 6 methods with concepts of recursion, iteration, exp(), pow(), etc. Try adding your own method and feel free to share it with us.

Share:

Author: Ayush Purawr