Power of Number using Recursion in Python

Power of Number using Recursion in Python

A function is said to be recursive when a particular function calls itself. Recursion is a method of programming or coding a problem, in which a function calls itself one or more times in its body. A recursive function is called by some external code. If the base condition is met then the program does something meaningful and exits. Otherwise, the function does some required processing and then calls itself to continue recursion. Here is an example of a recursive function used to calculate the power of a number. power of a number is how many times we repeat the number in the multiplication.

def pow(x, y):
    if y == 1:
        return x
    else:
        return pow(x, y-1) * x

if __name__ == '__main__':
    x = 2  #base
    y = 3   #power
    result = pow(x, y)
    print(x," to the power ", y, " is: ", result)

    x = 3 #base
    y = 3  #power
    result = pow(x, y)
    print(x," to the power ", y, " is: ", result)
    
    x = 4 #base
    y = 5  #power
    result = pow(x, y)
    print(x," to the power ", y, " is: ", result)

STEP 1: In this step, we will define a function to find the power of a number.

STEP 2: In this step, let’s see whether the function accepts the base(x).

STEP 3: In this step, let’s check whether the function accepts the power(y).

STEP 4: In this step, checking whether the function accepts both power and base and return the power of y with respect to x

STEP 5: In this step, use the main code and give the values of power and base and print the result.

OUTPUT:

2  to the power  3  is:  8

3  to the power  3  is:  27

4  to the power  5  is: 1024

 

1 Response

  1. Rohan says:

    CHeck the base condition this won’t work for pow(a,b) -> b=0
    Put if y == 0: return 1 instead of y == 1

Leave a Reply

Your email address will not be published. Required fields are marked *