Editor

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

power_of_a_number.py
base = 3 # or: base = int(input("Enter the base: "))
exponent = 4 # or: exponent = int(input("Enter the exponent: "))
result = 1
for i in range(exponent):
result *= base # multiply by the base once per step
print(f"{base} to the power {exponent} = {result}")
print(f"Using the ** operator: {base ** exponent}")
print(f"Using pow(): {pow(base, exponent)}")
Output
3 to the power 4 = 81
Using the ** operator: 81
Using pow(): 81

How it works

  1. result starts at 1, because multiplying by 1 changes nothing and any number to the power 0 is 1.
  2. The loop runs exponent times and multiplies result by base each time: 3, 9, 27, 81.
  3. base ** exponent is the power operator, and pow(base, exponent) is the same as a function.
  4. 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

Using recursion
def power(base, exponent):
if exponent == 0:
return 1
return base * power(base, exponent - 1)
print("2^10 =", power(2, 10))
print("5^3 =", power(5, 3))
Output
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

Negative and decimal exponents
import math
print("2 ** -2 =", 2 ** -2)
print("8 ** (1/3) =", 8 ** (1 / 3))
print("math.pow(2, 10) =", math.pow(2, 10))
print("pow(2, 10, 1000) =", pow(2, 10, 1000))
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises