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


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

Updated on: 02-Mar-2020

718 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements