Open In App

Python program to find power of a number

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of finding the power of a number in Python involves calculating the result of raising a base number to an exponent. For example, if we have a base 2 and an exponent 3, the result is [Tex]2^3=8[/Tex] .

Using ** operator

This is the simplest and most Pythonic way to calculate the power of a number. The ** operator is internally optimized and is the preferred choice for most situations.

Python
N, X = 2, 3 

res = N ** X 
print(res)

Output
8

Explanation: The expression res = N ** X is used to calculate the power of N raised to X using Python’s exponentiation operator ** . This evaluates to [Tex] 2^3=8[/Tex] .

Using pow()

pow() function is another efficient built-in method. It performs the same task as **, with the added advantage of supporting modular arithmetic for advanced use cases.

Python
N, X = 2, 3  

res = pow(N, X)
print(res)

Output
8

Explanation: pow() function in res = pow(N, X) computes 2^3 =8, raising N to the power X.

Using recursion

This approach uses recursion to divide the exponent into halves and reduce the number of operations. It is an elegant solution but involves a function call stack, which increases space complexity.

Python
def power(N, X):
    if X == 0:
        return 1  # base case
        
    half = power(N, X // 2)  # recursive call to get half power
    if X % 2 == 0:
        return half * half  # if even, multiply half powers
    else:
        return half * half * N  # if odd, multiply extra N

N, X = 2, 3  # initialize base (N) and exponent (X)
print(power(N, X))

Output
8

Explanation: This program defines a recursive function power(N, X) to calculate [Tex]N^X[/Tex] . It returns 1 if X is 0. It divides the problem into halves using power(N, X // 2), multiplying results accordingly. If X is even, it returns half * half; if odd, half * half * N.

Using loop

This is the most straightforward method, using a loop to multiply the base N repeatedly X times. While easy to understand, it is inefficient for large exponents.

Python
N, X = 2, 3 
P = 1  # initialize result

for i in range(X):  # loop X times
    P = P * N 
print(P)

Output
8

Explanation: for loop runs X times (3 times), and in each iteration, P is multiplied by N. This results in 2×2×2=8.



Next Article
Article Tags :
Practice Tags :

Similar Reads