Python Program to Calculate the Power of a Number
Beginner · Numbers
The power of a number, written base^exponent, means multiplying the base by itself exponent times: 2^5 = 2 x 2 x 2 x 2 x 2 = 32. This program works out a power with a loop and checks it against Python's built-in ways.
Program
3 to the power 4 = 81 Using the ** operator: 81 Using pow(): 81
How it works
resultstarts at 1, because multiplying by 1 changes nothing and any number to the power 0 is 1.- The loop runs
exponenttimes and multipliesresultbybaseeach time: 3, 9, 27, 81. base ** exponentis the power operator, andpow(base, exponent)is the same as a function.- The loop only handles whole exponents of 0 or more, while
**also works with negative and decimal exponents.
Other ways to write it
Using recursion
2^10 = 1024 5^3 = 125
Each call multiplies by the base once and asks for a power one lower, until the exponent reaches 0.
Negative and decimal exponents
2 ** -2 = 0.25 8 ** (1/3) = 2.0 math.pow(2, 10) = 1024.0 pow(2, 10, 1000) = 24
A negative exponent gives a fraction and 1/3 gives a cube root. math.pow() always returns a decimal, and pow() with a third number gives the remainder of the power, which is used in cryptography.
Try it yourself
Print the powers of 2 from 2^0 up to 2^10 in a loop.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises