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
resultstarts at 1 and is multiplied bybaseonce for each step of the loop.- Any number to the power 0 is 1. With
exponent = 0the loop does not run, so the function returns 1. - A negative exponent means "1 divided by the positive power": 2⁻³ = 1 / 2³ = 1/8 = 0.125. The loop uses
abs(exponent), and the division happens at the end. power(0, -1)raises aZeroDivisionError, which is correct: 1 / 0 has no value. Python's0 ** -1does the same.
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
- When the exponent is odd, one copy of
basegoes intoresult, so the rest has an even exponent. base *= basesquares the base andexponent //= 2halves the exponent.- This version is for exponents of 0 or more. Python's own
**uses the same idea for whole numbers.