Calculate Power Without Using pow() in Python
Build 2³ one multiplication at a time in Python, without pow or **. Beginner traces cover the accumulator, zero exponents, reciprocals, and a zero-base trap.
1# Program to calculate a^b without using pow() or ** for the core logic23base = float(input("Enter the base (a): "))4exponent = int(input("Enter the exponent (b, integer): "))56result = 178if exponent >= 0:9 for _ in range(exponent):10 result *= base11else:12 for _ in range(-exponent):13 result *= base14 result = 1 / result1516print(f"{base} raised to the power {exponent} is {result}")
Sample Output
2.0 raised to the power 3 is 8.0
Three multiplications of 2.0 change the accumulator from 1 to 8.0.
In this one
- Initialize a multiplication accumulator
- Handle a zero exponent
- Take a reciprocal for negative exponents
How it works
- 1
Read a float base and integer exponent; initialize result to 1.
- 2
Multiply result by base abs(exponent) times in the selected loop.
- 3
For negative exponents take 1 / result, then print the f-string.
Edge cases
Zero exponent
Enter exponent 0.
The loop does not run and result stays 1.
Zero to a negative power
Enter base 0 and exponent -1.
The reciprocal divides by zero and raises ZeroDivisionError.
What's going on
2 ** 3 already exists. This loop opens the lid: begin at 1, then multiply by the base once per exponent step. For 2 cubed, result goes 1, 2, 4, 8.
A non-negative exponent uses range(exponent). Zero means no repetitions, leaving 1, which matches Python's convention even for 0 to the power 0. For a negative exponent, the second loop computes the corresponding positive power and then takes its reciprocal.
2 to the power -3 becomes 1/8, or 0.125. A zero base with a negative exponent is undefined and this code raises ZeroDivisionError. Each extra exponent step needs another multiplication, so this is a teaching version, not an efficient power algorithm for huge exponents. ^ is still XOR, not power.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why does result start at 1?
Pick an answer to check it.
Question 2
How is a negative exponent handled?
Pick an answer to check it.
Questions people ask
Why does result start at 1?
One is the multiplication identity, so it preserves the first multiplied base.
How is a negative exponent handled?
The code computes the positive power, then divides 1 by that result.
Can exponent be 2.5 here?
No. int reads an integer exponent; this algorithm does not calculate fractional powers.