How to Find the Power of a Number Using Recursion in Python?

PythonServer Side ProgrammingProgramming

Following program accepts a number and index from user. The recursive funcion rpower() uses these two as arguments. The function multiplies the number repeatedly and recursively to return power.

Example

def rpower(num,idx):
    if(idx==1):
       return(num)
    else:
       return(num*rpower(num,idx-1))
base=int(input("Enter number: "))
exp=int(input("Enter index: "))
rpow=rpower(base,exp)
print("{} raised to {}: {}".format(base,exp,rpow))

Output

Here is a sample run −

Enter number: 10
Enter index: 3
10 raised to 3: 1000
raja
Published on 06-Mar-2018 20:51:18
Advertisements