Finding the power of a number using recursion in Python
A recursive function is a function that continuously calls itself. Here, in this tutorial, we are seeing how to find the power of a number using a recursive function in Python.
How to find the power of a number using recursion in Python
The function that we are making is going to take a base number and an exponent as the argument and the function further works as following:
- Pass the arguments to the recursive function to find the power of the number.
- Give the base condition for the case where we have the exponent argument as 1.
- If the exponent is not equal to 1, return the base multiplied by the function with base and exponent minus 1 as parameter.
- The function calls itself until the exponent value is 1.
- Print the power of the given base number.
def power(base,expo): if(expo==1): return(base) if(expo!=1): return(base*power(base,expo-1)) base=5 expo=3 print("Result:",power(base,expo)) base=12 expo=1 print("Result:",power(base,expo))
Result: 125 Result: 12
Here for the first set of inputs, the function runs recursively whereas, in the second set of inputs the base value is 1 and therefore, the first if the condition is satisfied and output comes.
Also read: Neon numbers in a range in Python