Calculate Power Without Using pow() in Python
Multiply in a loop. Negative exponents: do the positive power, then 1/result.
BeginnerBasic Python ProgramsExample 21 of 25
calculate-power-without-using-pow.py
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}")
Output
Enter the base (a): 2 Enter the exponent (b, integer): 3 2.0 raised to the power 3 is 8.0
In this one
- loop multiply, start from 1
- negative exponent = 1 / positive power
What's going on
2 ** 3 exists. This loop is so you can see exponentiation is repeated multiply.
result = 1, then multiply by base, exponent times. 2³: 1→2→4→8.
Negative exponent: compute the positive one, then 1 / result. 2⁻³ is 0.125.
^ is still XOR. I will keep saying that until it sticks.
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.