Tutorialspoint

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

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


1 Answer
Jayashree
, 91 Views

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.

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))

Here is a sample run:

Enter number: 10
Enter index: 3
10 raised to 3: 1000
Advertisements