Calculate Power Without Using pow()

Raise a number to an integer power using a loop instead of the built-in pow() or **.

PythonBeginner

What You'll Learn

  • Using loops to implement exponentiation
  • Handling negative exponents manually
  • Working with both float bases and int exponents
Python
# Program to calculate a^b without using pow() or ** for the core logic

base = float(input("Enter the base (a): "))
exponent = int(input("Enter the exponent (b, integer): "))

result = 1

if exponent >= 0:
    for _ in range(exponent):
        result *= base
else:
    for _ in range(-exponent):
        result *= base
    result = 1 / result

print(f"{base} raised to the power {exponent} is {result}")

Output

Enter the base (a): 2
Enter the exponent (b, integer): 3
2.0 raised to the power 3 is 8.0

We simulate exponentiation by repeated multiplication:

  • For non-negative exponents, multiply the base by itself exponent times.
  • For negative exponents, compute the positive power and then take its reciprocal.

This illustrates how higher-level operations can be built from simple loops.

Step-by-Step Breakdown

  1. 1Read base and integer exponent.
  2. 2Initialize result to 1.
  3. 3If exponent is non-negative, loop exponent times multiplying result by base.
  4. 4If exponent is negative, loop -exponent times, then invert result.
  5. 5Print the final result.