Calculate Power Without Using pow()

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

BeginnerTopic: Basic Python Programs
Back

What You'll Learn

  • Using loops to implement exponentiation
  • Handling negative exponents manually
  • Working with both float bases and int exponents

Python Calculate Power Without Using pow() Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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

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.

Understanding Calculate Power Without Using pow()

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.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.