Python Program to Compute the Power of a Number – 2024

Hey guys, in this blog we will see a Python Program to Compute the Power of a Number.

Example 1: Calculate the power of a number using a while loop

# Python Program to Compute the Power of a Number

base = 5
exponent = 4

result = 1

while exponent != 0:
    result *= base
    exponent-=1

print("Answer = " + str(result))

Output

Answer = 625
  • Here we are using a while loop to calculate the power of a number.
  • It just keeps on multiplying the base number exponential times.
  • It is the most brute-force approach.

Example 2: Calculate the power of a number using a for loop

base = 5
exponent = 4

result = 1

for exponent in range(exponent, 0, -1):
    result *= base

print("Answer = " + str(result))

Output

Answer = 625
  • Here we are using a for loop to calculate the power of a number.
  • It is almost similar to the above approach.
  • It just keeps on multiplying the base number exponential times.
  • It is also a brute-force approach.
  • Our for loop will go like 4,3,2,1.

Example 3: Calculate the power of a number using the pow() function

base = 5
exponent = -4

result = pow(base, exponent)

print("Answer = " + str(result))

Output

Answer = 0.0016
  • The easiest way to find the power of a number is by using the pow() function.
  • It takes two arguments base and exponent.

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *