Open In App

Python program to find power of a number

Last Updated : 23 Jul, 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 2^3=8 .

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 2^3=8 .

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 N^X . 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.


Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy