Algorithm


  1. Input:

    • Accept the base (the number to be raised) and the exponent (the power to which the base is raised) as input.
  2. Initialize result:

    • Set a variable result to 1. This will be used to accumulate the result.
  3. Loop for exponent times:

    • Use a loop to iterate from 1 to the exponent.
    • In each iteration, multiply the result by the base.
  4. Output:

    • After the loop, the result contains the power of the number.
    • Print or return the result as the output.

 

Code Examples

#1 Code Example- Python Program Calculate power of a number using a while loop

Code - Python Programming

base = 3
exponent = 4

result = 1

while exponent != 0:
    result *= base
    exponent-=1

print("Answer = " + str(result))
Copy The Code & Try With Live Editor

Output

x
+
cmd
Answer = 81

#2 Code Example- Python Program Calculate power of a number using a for loop

Code - Python Programming

base = 3
exponent = 4

result = 1

for exponent in range(exponent, 0, -1):
    result *= base

print("Answer = " + str(result))
Copy The Code & Try With Live Editor

Output

x
+
cmd
Answer = 81

#3 Code Example- Python Program Calculate the power of a number using pow() function

Code - Python Programming

base = 3
exponent = -4

result = pow(base, exponent)

print("Answer = " + str(result))
Copy The Code & Try With Live Editor

Output

x
+
cmd
Answer = 0.012345679012345678
Advertisements

Demonstration


Python Programing Example to Compute the Power of a Number-DevsEnv