Python Program to Calculate the Power using Recursion

This is a Python Program to find the power of a number using recursion.

Problem Description

The program takes a base and a power and finds the power of the base using recursion.

Problem Solution

1. Take the base and exponential value from the user.
2. Pass the numbers as arguments to a recursive function to find the power of the number.
3. Give the base condition that if the exponential power is equal to 1, return the base number.
4. If the exponential power isn’t equal to 1, return the base number multiplied with the power function called recursively with the arguments as the base and power minus 1.
5. Print the final result.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the power of a number using recursion. The program output is also shown below.

def power(base,exp):
    if(exp==1):
        return(base)
    if(exp!=1):
        return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
Program Explanation

1. User must enter the base and exponential value.
2. The numbers are passed as arguments to a recursive function to find the power of the number.
3. The base condition is given that if the exponential power is equal to 1, the base number is returned.
4. If the exponential power isn’t equal to 1, the base number multiplied with the power function is called recursively with the arguments as the base and power minus 1.
5. The final result is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter base: 2
Enter exponential value: 5
Result: 32
 
Case 2:
Enter base: 5
Enter exponential value: 3
Result: 125

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.