PythonMastery

Power of a number in Python without pow()

Raise a number to a power with a loop instead of ** or pow(), handle zero and negative exponents, and see the faster squaring method.

Python already has ** and pow() for powers: 2 ** 10 is 1024. Writing the calculation yourself shows what a power means: 2¹⁰ is 2 multiplied by itself 10 times.

The program

python
def power(base, exponent):
    result = 1
    for _ in range(abs(exponent)):
        result *= base
    if exponent < 0:
        return 1 / result
    return result


print(power(2, 10))
print(power(3, 4))
print(power(5, 0))
print(power(2, -3))
output
1024
81
1
0.125

How it works

Another way: exponentiation by squaring

The loop above needs 1,000 multiplications for an exponent of 1,000. Exponentiation by squaring needs only about 20. It uses the fact that x¹⁰ = (x²)⁵, so it squares the base and halves the exponent at each step:

python
def fast_power(base, exponent):
    result = 1
    while exponent > 0:
        if exponent % 2 == 1:
            result *= base
        base *= base
        exponent //= 2
    return result


print(fast_power(2, 10))
print(fast_power(3, 200) == 3 ** 200)
output
1024
True

Learn the idea: Loops: for, while, and the Pythonic Patterns, Functions & Scoping